Server-side session in Next.js
Keep tokens in an httpOnly cookie, read the session in server components, and protect routes before they render.
What it shows
- One route handler under
/api/authadds the routeslogin,callback,sessionandlogout. - The link Sign in goes to the hosted sign-in page. The callback stores the tokens in the encrypted httpOnly cookie
lumo_session. proxy.tssends a signed-out visitor of/dashboardto sign-in, and it replaces an access token that is about to expire.- Server components read the session with
auth()and the profile withcurrentUser(). protectPage()protects/accountin the page itself, and/api/auth/logoutends the session.route.tswraps logout, so that no other site can sign the person out.
The server runs the whole exchange with LumoAuth. No token reaches the JavaScript of the browser.
Before you start
- Node.js 20 or later.
- An API key with the scopes
admin:clients:readandadmin:clients:write. Create it in the portal under Applications & developer tools, API keys. - A confidential application with the redirect URI
http://localhost:3000/api/auth/callback. The setup script creates it.
| Variable | Value |
|---|---|
LUMOAUTH_URL | The address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region. |
LUMOAUTH_ORG_ID | Your organization, for example acme-corp. |
LUMOAUTH_API_KEY | An API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it. |
APP_URL | Optional. The address of your app, when it is not http://localhost:3000. Only the setup script uses it. |
NEXT_PUBLIC_LUMOAUTH_DOMAIN | The address of LumoAuth. The setup script prints it from LUMOAUTH_URL. |
NEXT_PUBLIC_LUMOAUTH_ORG_ID | Your organization. The setup script prints it. |
NEXT_PUBLIC_LUMOAUTH_CLIENT_ID | The client ID of the application. The setup script prints it. |
LUMOAUTH_CLIENT_SECRET | The client secret of the application. The setup script prints it. |
LUMOAUTH_SECRET | At least 32 characters. The app encrypts the session cookie with it. The setup script prints a random value. |
The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.
node sign-in/nextjs-server-session/setup.mjs
setup.mjs
// Creates the application that the Next.js app signs in with: a confidential
// application with the callback address of the app. Run it again at any time.
//
// node sign-in/nextjs-server-session/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is http://localhost:3000.
import { randomBytes } from 'node:crypto';
import { call, list, org, printEnv, url } from '../../_lib/admin.mjs';
const appUrl = (process.env.APP_URL ?? 'http://localhost:3000').replace(/\/+$/, '');
const name = 'Next.js server session';
const redirectUris = [`${appUrl}/api/auth/callback`];
let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}
console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
NEXT_PUBLIC_LUMOAUTH_DOMAIN: url,
NEXT_PUBLIC_LUMOAUTH_ORG_ID: org,
NEXT_PUBLIC_LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
// The app encrypts its session cookie with this value.
LUMOAUTH_SECRET: randomBytes(32).toString('hex'),
});
Copy the export lines that the script prints into the terminal where you start the app.
Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:
- Open Applications and select Next.js server session.
- Open the Configuration tab and go to the section Logout.
- Under Post-logout redirect URIs, enter
http://localhost:3000/. - Select Save configuration.
Code
Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. The app was built and started with npm run build and npm start, and a browser signed in and out through the hosted page. A link and a form on another site did not sign the person out.
- Next.js
// The routes of the sign-in: /api/auth/login, /api/auth/callback,
// /api/auth/session and /api/auth/logout. The server runs the code exchange
// and keeps the tokens in an encrypted httpOnly cookie.
import { createRouteHandler } from '@lumoauth/nextjs/server';
const handler = createRouteHandler();
type Context = { params: Promise<{ lumoauth: string[] }> };
// Another site must not be able to sign a person out. A GET of logout signs
// out at once only when the browser says that it comes from this app or from
// a typed address. Any other GET of logout gets a page with a button.
export async function GET(request: Request, context: Context) {
const site = request.headers.get('sec-fetch-site');
const [action] = (await context.params).lumoauth;
if (action !== 'logout' || site === 'same-origin' || site === 'none') return handler.GET(request, context);
return new Response('<p>Do you want to sign out?</p><form method="post"><button>Sign out</button></form>', {
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'no-store',
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'same-origin',
// No form-action: Chromium applies it to the redirect to LumoAuth too.
'Content-Security-Policy': "default-src 'none'; frame-ancestors 'none'",
},
});
}
// The origin of the app as the browser sees it. request.url holds the address
// that Next.js listens on, which can differ, so read the request headers.
function appOrigin(request: Request) {
const protocol = request.headers.get('x-forwarded-proto') ?? new URL(request.url).protocol.slice(0, -1);
return `${protocol}://${request.headers.get('x-forwarded-host') ?? request.headers.get('host')}`;
}
// Only logout takes a POST, and it must come from a page of this app.
export async function POST(request: Request, context: Context) {
const origin = request.headers.get('origin');
const site = request.headers.get('sec-fetch-site');
if (origin && origin !== 'null' ? origin === appOrigin(request) : site === 'same-origin') {
return handler.POST(request, context);
}
return new Response('Sign-out refused: the request did not come from this app.', { status: 403 });
}
// Runs before each page. It sends a signed-out visitor of /dashboard to
// sign-in, and it replaces an access token that is about to expire.
// Next.js 16 names this file proxy.ts. Next.js 14 and 15 name it middleware.ts.
import { lumoAuthMiddleware } from '@lumoauth/nextjs/server';
export default lumoAuthMiddleware({ protect: ['/dashboard/:path*'] });
export const config = { matcher: ['/((?!_next|.*\\..*).*)'] };
// The home page, a server component. auth() reads the session cookie with
// no network call, so the page is correct in the first HTML that is sent.
import { auth, currentUser } from '@lumoauth/nextjs/server';
export default async function Home() {
const { isSignedIn } = await auth();
if (!isSignedIn) {
return (
<main>
<p>Nobody is signed in.</p>
<a href="/api/auth/login">Sign in</a>
</main>
);
}
// currentUser() asks the UserInfo endpoint, with the token of the session.
const user = await currentUser();
return (
<main>
<p>Signed in as {user?.email}.</p>
<p>
<a href="/dashboard">Dashboard</a> · <a href="/account">Account</a> · <a href="/api/auth/logout">Sign out</a>
</p>
</main>
);
}
// Protected in proxy.ts: a signed-out visitor never reaches this component.
import { auth } from '@lumoauth/nextjs/server';
export default async function Dashboard() {
const { userId, getToken } = await auth();
return (
<main>
<h1>Dashboard</h1>
<p>User ID: {userId}</p>
<p>The server holds an access token: {getToken() ? 'yes' : 'no'}</p>
<a href="/">Home</a>
</main>
);
}
// Protected in the page itself. protectPage() redirects a signed-out visitor
// to sign-in and brings the person back here afterwards.
import { protectPage } from '@lumoauth/nextjs/server';
export default async function Account() {
const { userId } = await protectPage({ returnTo: '/account' });
return (
<main>
<h1>Account</h1>
<p>User ID: {userId}</p>
<a href="/">Home</a>
</main>
);
}
cd sign-in/nextjs-server-session/js && npm install && npm run dev
Check the result
Open http://localhost:3000 in a browser, select Sign in, and sign in as a user of your organization.
Signed out
GET / 200 Nobody is signed in.
GET /dashboard 307 /api/auth/login?return_to=%2Fdashboard
GET /account 307 /api/auth/login?return_to=%2Faccount
Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
GET /account 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10
- The developer tools of the browser show the cookie
lumo_session, marked httpOnly. Local storage and session storage hold no token. - A signed-out request for
/dashboardgets a redirect, and none of the HTML of the page. - Sign out removes the cookie, ends the session at LumoAuth and returns to
/. The next visit to/dashboardshows the sign-in page again. - A link to
/api/auth/logouton another site shows a page with the question "Do you want to sign out?". The person stays signed in until they select Sign out. A form on another site that posts to the route gets 403.
Limits
- The package works with the App Router only.
proxy.tsandprotectPage()check that a valid session cookie exists. Your API must still check the token and the permissions of the person.auth()never refreshes a token, because a server component cannot write a cookie. Without the proxy file,getToken()returnsnullafter the access token expires.- Without the post-logout redirect URI, sign-out still ends the session. The person then stays on a page of LumoAuth that confirms it.
- Next.js 14 and 15 name the proxy file
middleware.ts. The content is the same.