Setup a cross-platform Electron app with typescript, nextjs and Okta as our identity solution.
To set up an Electron application with TypeScript, Next.js, and Okta, you will need to take the following steps:
Create a new Electron application using the electron-forge tool: Copy code
npx create-electron-app app --template=typescript
# Install the necessary dependencies for Next.js and Typescript
cd app && npm install react react-dom next @types/react @types/react-dom
Next, configure Next.js in the application's main process:
// main.ts
import { app, BrowserWindow } from 'electron';
import * as next from 'next';
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const mainWindow = new BrowserWindow({
width: 800,
height: 600,
});
mainWindow.loadURL('http://localhost:3000');
mainWindow.webContents.on('did-finish-load', () => {
mainWindow.webContents.executeJavaScript(`
document.body.style.cssText = 'background: #fff;';
`);
});
});
Create a new file server.ts in the root directory of your project and add the following code:
import {createServer} from 'http'
import next from 'next'
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
app.prepare().then(() => {
createServer((req, res) => {
handle(req, res)
}).listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
Now, install Okta and its related dependencies
npm install @okta/okta-react @okta/okta-signin-widget
Create a new file Auth.tsx in the root directory of your project and add the following code:
import { useEffect, useState } from 'react';
import { useOktaAuth } from '@okta/okta-react';
interface User {
email: string;
name: string;
}
export const Auth = () => {
const { authState, authService } = useOktaAuth();
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
if (!authState.isAuthenticated) {
setUser(null);
} else {
authService.getUser().then((user: any) => {
setUser(user);
});
}
}, [authState, authService]);
return (
<div>
{authState.isAuthenticated && (
<div>
<h1>Welcome {user?.name}!</h1>
At this point were ready to test our setup.