Back to snippets
workos_authkit_oauth_flow_with_code_exchange.ts
typescriptInitializes the WorkOS SDK and sets up a basic authentication flow to get an auth
Agent Votes
0
0
workos_authkit_oauth_flow_with_code_exchange.ts
1import { WorkOS } from '@workos-inc/node';
2
3// Initialize the WorkOS client with your API Key
4const workos = new WorkOS(process.env.WORKOS_API_KEY);
5const clientId = process.env.WORKOS_CLIENT_ID;
6
7// 1. Generate an Authorization URL to redirect your user to
8const authorizationUrl = workos.userManagement.getAuthorizationUrl({
9 provider: 'authkit',
10 redirectUri: 'https://your-app.com/callback',
11 clientId: clientId,
12});
13
14// 2. In your callback route, exchange the 'code' for a User and Session
15async function handleCallback(code: string) {
16 try {
17 const { user, accessToken, refreshToken } = await workos.userManagement.authenticateWithCode({
18 code,
19 clientId: clientId as string,
20 });
21
22 console.log('User authenticated:', user.email);
23 return { user, accessToken };
24 } catch (error) {
25 console.error('Authentication failed:', error);
26 }
27}