Easy to use authentication APIs designed to provide a flexible, secure, and fast integration.
Integrating User Management features into your app is quick and easy. In this guide, we’ll walk you through adding a hosted authentication flow to your application using AuthKit.
In addition to this guide, there are a variety of example apps available to help with your integration.
To get the most out of this guide, you’ll need:
Let’s add the necessary dependencies and configuration in your WorkOS Dashboard.
For a Next.js integration, use the authkit-nextjs
library. Start by installing it in your Next.js project via npm
.
npm install @workos-inc/authkit-nextjs
A redirect URI is a callback endpoint that WorkOS will redirect to after a user has authenticated. This endpoint will exchange the authorization code returned by WorkOS for an authenticated User object. We’ll create this endpoint in the next step.
You can set a redirect URI in the Redirects section of the WorkOS Dashboard. While wildcards in your URIs can be used in the staging environment, they and query parameters cannot be used in production.
When users sign out of their application, they will be redirected to your app’s homepage which is configured in the same dashboard area.
To make calls to WorkOS, provide the API key and the client ID. Store these values as managed secrets and pass them to the SDKs either as environment variables or directly in your app’s configuration depending on your preferences.
WORKOS_API_KEY='sk_example_123456789' WORKOS_CLIENT_ID='client_123456789' WORKOS_COOKIE_PASSWORD="<your password>" # generate a secure password here # configured in the WorkOS dashboard NEXT_PUBLIC_WORKOS_REDIRECT_URI="http://localhost:3000/callback"
The NEXT_PUBLIC_WORKOS_REDIRECT_URI
uses the NEXT_PUBLIC
prefix so the variable is accessible in edge functions and middleware configurations. This is useful for configuring operations like Vercel preview deployments.
The SDK requires you to set a strong password to encrypt cookies. This password must be at least 32 characters long. You can generate a secure password by using the 1Password generator or the openssl
library via the command line:
openssl rand -base64 24
The code examples use your staging API keys when signed in
The AuthKitProvider
component adds protections for auth edge cases and is required to wrap your app layout.
import { AuthKitProvider } from '@workos-inc/authkit-nextjs'; export default function RootLayout({ children }) { return ( <html lang="en"> <body> <AuthKitProvider>{children}</AuthKitProvider> </body> </html> ); }
Next.js middleware is required to determine which routes require authentication.
import { authkitMiddleware } from '@workos-inc/authkit-nextjs'; export default authkitMiddleware(); // Match against pages that require authentication // Leave this out if you want authentication on every page in your application export const config = { matcher: ['/'] };
When a user has authenticated via AuthKit, they will be redirected to your app’s callback route. Make sure this route matches the WORKOS_REDIRECT_URI
environment variable and the configured redirect URI in your WorkOS dashboard.
import { handleAuth } from '@workos-inc/authkit-nextjs'; // Redirect the user to `/` after successful sign in // The redirect can be customized: `handleAuth({ returnPathname: '/foo' })` export const GET = handleAuth();
We’ll need to direct users to sign in (or sign up) using AuthKit before redirecting them back to your application. We’ll do this by generating an AuthKit authorization URL server side and redirecting the user to it.
The withAuth
method is used to retrieve the current logged in user and their details.
import Link from 'next/link'; import { getSignInUrl, getSignUpUrl, withAuth, } from '@workos-inc/authkit-nextjs'; export default async function HomePage() { // Retrieves the user from the session or returns `null` if no user is signed in const { user } = await withAuth(); // Get the URL to redirect the user to AuthKit to sign in const signInUrl = await getSignInUrl(); // Get the URL to redirect the user to AuthKit to sign up const signUpUrl = await getSignUpUrl(); /** * If a signed-in user is mandatory, you can use the `ensureSignedIn` * configuration option. If logged out, the below will immediately redirect * the user to AuthKit. After signing in, the user will automatically * be redirected back to this page. * */ // const { user } = await withAuth({ ensureSignedIn: true }); if (!user) { return ( <> <Link href={signInUrl}>Sign in</Link>; <Link href={signUpUrl}>Sign up</Link>; </> ); } return ( <> <p>Welcome back{user.firstName && `, ${user.firstName}`}</p> </> ); }
For routes where a signed in user is mandatory, you can use the ensureSignedIn
option when using withAuth
.
import { withAuth } from '@workos-inc/authkit-nextjs'; export default async function ProtectedPage() { // If the user isn't signed in, they will be automatically redirected to AuthKit const { user } = await withAuth({ ensureSignedIn: true }); return ( <> <p>Welcome back{user.firstName && `, ${user.firstName}`}</p> </> ); }
If you prefer a “secure by default” approach where every route is automatically protected, look into implementing middleware auth mode in the authkit-nextjs
library.
Finally, ensure the user can end their session by redirecting them to the logout URL. After successfully signing out, the user will be redirected to your app’s homepage, which is configured in the WorkOS dashboard.
import Link from 'next/link'; import { getSignInUrl, getSignUpUrl, withAuth, signOut, } from '@workos-inc/authkit-nextjs'; export default async function HomePage() { // Retrieves the user from the session or returns `null` if no user is signed in const { user } = await withAuth(); // Get the URL to redirect the user to AuthKit to sign in const signInUrl = await getSignInUrl(); // Get the URL to redirect the user to AuthKit to sign up const signUpUrl = await getSignUpUrl(); if (!user) { return ( <> <Link href={signInUrl}>Sign in</Link>; <Link href={signUpUrl}>Sign up</Link>; </> ); } return ( <form action={async () => { 'use server'; await signOut(); }} > <p>Welcome back{user.firstName && `, ${user.firstName}`}</p> <button type="submit">Sign out</button> </form> ); }
If you haven’t configured your app’s homepage in the WorkOS dashboard, users will see an error when logging out.
Navigate to the authentication endpoint we created and sign up for an account. You can then sign in with the newly created credentials and see the user listed in the Users section of the WorkOS Dashboard.