Add authentication to your Next.js (Pages Router) application
- The sample project is available on our SDK repository.
- The example is based on Next.js Pages Router.
Prerequisites
- A Logto Cloud account or a self-hosted Logto.
- A Logto traditional application created.
Installation
Install Logto SDK via your favorite package manager:
- npm
- pnpm
- yarn
npm i @logto/nextpnpm add @logto/nextyarn add @logto/nextIntegration
Init LogtoClient
Import and initialize LogtoClient:
import LogtoClient from '@logto/next';
export const logtoClient = new LogtoClient({
appId: '<your-application-id>',
appSecret: '<your-app-secret-copied-from-console>',
endpoint: '<your-logto-endpoint>', // E.g. http://localhost:3001
baseUrl: 'http://localhost:3000',
cookieSecret: 'complex_password_at_least_32_characters_long',
cookieSecure: process.env.NODE_ENV === 'production',
});
Configure Redirect URIs
Before we dive into the details, here's a quick overview of the end-user experience. The sign-in process can be simplified as follows:
- Your app invokes the sign-in method.
- The user is redirected to the Logto sign-in page. For native apps, the system browser is opened.
- The user signs in and is redirected back to your app (configured as the redirect URI).
Regarding redirect-based sign-in
- This authentication process follows the OpenID Connect (OIDC) protocol, and Logto enforces strict security measures to protect user sign-in.
- If you have multiple apps, you can use the same identity provider (Logto). Once the user signs in to one app, Logto will automatically complete the sign-in process when the user accesses another app.
To learn more about the rationale and benefits of redirect-based sign-in, see Logto sign-in experience explained.
In the following code snippets, we assume your app is running on http://localhost:3000/.
Configure redirect URIs
Switch to the application details page of Logto Console. Add a redirect URI http://localhost:3000/api/logto/sign-in-callback.
Just like signing in, users should be redirected to Logto for signing out of the shared session. Once finished, it would be great to redirect the user back to your website. For example, add http://localhost:3000/ as the post sign-out redirect URI section.
Then click "Save" to save the changes.
Prepare API routes
Prepare API routes to connect with Logto.
Go back to your IDE/editor, use the following code to implement the API routes first:
import { logtoClient } from '../../../libraries/logto';
export default logtoClient.handleAuthRoutes();
This will create 4 routes automatically:
/api/logto/sign-in: Sign in with Logto./api/logto/sign-in-callback: Handle sign-in callback./api/logto/sign-out: Sign out with Logto./api/logto/user: Check if user is authenticated with Logto, if yes, return user info.
Implement sign-in and sign-out
We have prepared the API routes, now let's implement the sign-in and sign-out buttons in your home page. We need to redirect the user to the sign-in or sign-out route when needed. To help with this, use useSWR to fetch authentication status from /api/logto/user.
Check this guide to learn more about useSWR.
import { type LogtoContext } from '@logto/next';
import useSWR from 'swr';
const Home = () => {
const { data } = useSWR<LogtoContext>('/api/logto/user');
return (
<nav>
{data?.isAuthenticated ? (
<p>
Hello, {data.claims?.sub},
<button
onClick={() => {
window.location.assign('/api/logto/sign-out');
}}
>
Sign Out
</button>
</p>
) : (
<p>
<button
onClick={() => {
window.location.assign('/api/logto/sign-in');
}}
>
Sign In
</button>
</p>
)}
</nav>
);
};
export default Home;
Checkpoint: Test your application
Now, you can test your application:
- Run your application, you will see the sign-in button.
- Click the sign-in button, the SDK will init the sign-in process and redirect you to the Logto sign-in page.
- After you signed in, you will be redirected back to your application and see the sign-out button.
- Click the sign-out button to clear token storage and sign out.
Get user information
Display user information
When user is signed in, there are three ways to get user information.
Through API request in front-end
import { type LogtoContext } from '@logto/next';
import { useMemo } from 'react';
import useSWR from 'swr';
const Home = () => {
const { data } = useSWR<LogtoContext>('/api/logto/user');
const claims = useMemo(() => {
if (!data?.isAuthenticated || !data.claims) {
return null;
}
return (
<div>
<h2>Claims:</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{Object.entries(data.claims).map(([key, value]) => (
<tr key={key}>
<td>{key}</td>
<td>{String(value)}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}, [data]);
return (
<div>
{claims}
</div>
);
};
export default Home;
Through getServerSideProps
import { LogtoContext } from '@logto/next';
import { logtoClient } from '../../libraries/logto';
type Props = {
user: LogtoContext;
};
const Home = ({ user }: Props) => {
const claims = useMemo(() => {
if (!user.isAuthenticated || !user.claims) {