Next.js Quickstart

This is a quickstart guide to help you integrate Descope with your Next.js application. Follow the steps below to get started.

Install NextJS SDK

Install the SDK with the following command:

Terminal
npm i --save @descope/nextjs-sdk

Import AuthProvider from Frontend SDK

Next step is to import all of the built-in functions you will want to use from Descope NextJS SDK.

app/sign-in.tsx
import { Descope } from '@descope/nextjs-sdk';
 
const Page = () => {
	return (<div></div>);
};

Wrap application with AuthProvider

Wrap the entire application with <AuthProvider />. You need your Project ID for this step, which you can take from the snippet on the right.

Note

You can also add the optional baseUrl parameter if you're utilizing a CNAME within your Descope project (ex: https://auth.company.com).

app/layout.tsx
import { AuthProvider } from '@descope/nextjs-sdk';
 
export default function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) {
	return (
		<AuthProvider projectId="__ProjectID__">
			<html lang="en">
				<body>{children}</body>
			</html>
		</AuthProvider>
	);
}

Add Flows Component

To trigger the Descope Flow, you will need to add this component. The screens you've customized in your Flow will appear here. You can also customize the component with the following:

  • flowId: ID of the flow you wish to use
  • onSuccess and onError: functions that execute when authentication succeeds or fails

Note

Descope stores the last user information in local storage. If you wish to disable this feature, you can pass store-last-authenticated-user as false to the AuthProvider component. Please note that some features related to the last authenticated user may not function as expected if this behavior is disabled.

app/sign-in.tsx
import { Descope } from '@descope/nextjs-sdk';
// you can choose flow to run from the following without `flowId` instead
// import { SignInFlow, SignUpFlow, SignUpOrInFlow } from '@descope/nextjs-sdk'
 
const Page = () => {
	return (
		<Descope
			flowId="sign-up-or-in"
			onSuccess={(e) => console.log('Logged in!')}
			onError={(e) => console.log('Could not logged in!')}
			redirectAfterSuccess="/"
			// redirectAfterError="/error-page"
		/>
	);
};

Getting User Details

To extract details on the user, you can load the user details from e.detail.user. On successful authentication, the information about the user is returned and accessible with e.detail.user.

  • onSuccess: function that executes when authentication succeeds

For example:

app/sign-in.tsx
import { Descope } from '@descope/nextjs-sdk';
// you can choose flow to run from the following without `flowId` instead
// import { SignInFlow, SignUpFlow, SignUpOrInFlow } from '@descope/nextjs-sdk'
 
const Page = () => {
	return (
		<Descope
			flowId="sign-up-or-in"
			onSuccess={(e) => {
				console.log(e.detail.user.name);
				console.log(e.detail.user.email);
			}}
			redirectAfterSuccess="/"
		/>
	);
};

Alternatively, you can also use the me function which fetches the current authenticated user information.

Utilize the NextJS SDK Hooks and Functions

Descope provides many different hooks to check if the user is authenticated, session is loading etc. You can use these to customize the user experience:

  • isAuthenticated: is user authenticated?
  • isSessionLoading: This is used for implementing loading screens while sessions are being established
  • user: user object that contains all user attributes (email, name, etc.)
  • isUserLoading: This is used for implementing loading screens while user objects are being loaded
  • getSessionToken(): This gets the session token from your browser which you can include in your backend requests
app/page.tsx
'use client';
 
import { useCallback } from 'react';
import { useDescope, useSession, useUser } from '@descope/nextjs-sdk/client';
 
const Page = () => {
	// NOTE - `useDescope`, `useSession`, `useUser` should be used inside `AuthProvider` context,
	// and will throw an exception if this requirement is not met
	const { isAuthenticated, isSessionLoading, sessionToken } = useSession();
 
	// useUser retrieves the logged in user information
	const { user } = useUser();
	
	// useDescope retrieves Descope SDK for further operations related to authentication
	// such as logout
	const sdk = useDescope();
 
	const handleLogout = useCallback(() => {
		sdk.logout();
	}, [sdk]);
		
	if (isSessionLoading || isUserLoading) {
		return <p>Loading...</p>;
	}
 
	if (isAuthenticated) {
		return (
			<>
				<p>Hello {user.name}</p>
				<button onClick={handleLogout}>Logout</button>
			</>
		);
	}
 
	return (
		<>
			<p>You are not logged in</p>
		</>
	);
}

Setting Up the Middleware

You can use NextJS Middleware to require authentication for specific pages and routes in your application. The Descope SDK provides a middleware function that can be used to require authentication for your protected pages and routes. Read more about the Next SDK here

app/middleware.ts
import { authMiddleware } from '@descope/nextjs-sdk/server'
 
export default authMiddleware({
	// The Descope project ID to use for authentication
	// Defaults to process.env.DESCOPE_PROJECT_ID
	projectId: '__ProjectID__',
 
	// The URL to redirect to if the user is not authenticated
	// Defaults to process.env.SIGN_IN_ROUTE or '/sign-in' if not provided
	redirectUrl?: string,
 
	// An array of public routes that do not require authentication
	// In addition to the default public routes:
	// - process.env.SIGN_IN_ROUTE or /sign-in if not provided
	// - process.env.SIGN_UP_ROUTE or /sign-up if not provided
	// NOTE: In case it contains query parameters that exist in the original URL,
	// they will override the original query parameters. e.g. if the original URL is /page?param1=1&param2=2 and the redirect URL is /sign-in?param1=3,
	// the final redirect URL will be /sign-in?param1=3&param2=2
	publicRoutes?: string[]
 
})
 
export const config = {
	matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)']
}

Congratulations

Now that you've got the authentication down, go focus on building out the rest of your app!


Checkpoint

Your application is now integrated with Descope. Please test with sign-up or sign-in use case.

Need help?

Customize

Now that you have the end-to-end application working, you can choose to configure and personalize many different areas of Descope, including your brand, style, custom user authentication journeys, etc. We recommend starting with customizing your user-facing screens, such as signup and login.

Was this helpful?

On this page