Make the current session available to all downstream handlers.
Express middleware
Auth.js · Function
In Auth.js Express, getSession resolves the session associated with an incoming request. Use it in middleware or route handling, then check the result before serving protected content.
Call getSession with an Express request and Auth.js configuration to resolve the current session. The result can be used for authorization or exposed to templates and routes through middleware; when no authenticated session exists, the result is absent.
function getSession(req, config): GetSessionResult| Name | Type | Description |
|---|---|---|
req | Request | The incoming Express request used to resolve the session. |
config | ExpressAuthConfig | Auth.js configuration for the Express integration. |
GetSessionResult
import { getSession } from "@auth/express"
export async function authSession(req, res, next) {
res.locals.session = await getSession(req)
next()
}This middleware resolves the request's session and makes it available to later Express handlers through res.locals.
Express middleware
Protected routes
Server-rendered templates
getSession(req, config) reads the current session for an Express request and returns a GetSessionResult. Middleware can store that result in res.locals so subsequent handlers can use it.
Follow-up: How would you protect a route? Check the session or its user, redirect when it is absent, and call next only for an authenticated request.
The request is the required input, while the Auth.js Express configuration supplies the authentication settings. The function returns GetSessionResult, which represents the resolved session result.
Follow-up: Why pass configuration explicitly? The Express API needs the application’s Auth.js configuration to evaluate the request against the configured authentication setup.
A common pattern is middleware that assigns await getSession(req) to res.locals.session, followed by route handlers that read that value. This makes session data available across routes and to template rendering.
Follow-up: How should a route handle a missing session? Test for session?.user and redirect to login instead of rendering protected content.
authuseSessionSessionProviderGetSessionResultExpressAuthConfig