Protect authenticated pages
Require a signed-in session before allowing a page request.
Auth.js · Function
The authorized callback controls access when Auth.js Middleware evaluates a request. Return an authorization decision for normal flow, or a NextResponse for custom redirects and responses.
The authorized callback runs when Middleware needs to decide whether a request may proceed. It receives the current authentication state and request, and can return a boolean or a custom NextResponse to allow, deny, redirect, or otherwise handle the request.
authorized: (params) => any| Name | Type | Description |
|---|---|---|
params.auth | null | Session | The authenticated user or token, if available; otherwise null. |
params.request | NextRequest | The incoming request to evaluate. |
any; commonly a boolean authorization decision or a NextResponse for custom handling.
callbacks.authorized and receives one parameter object.request parameter identifies the incoming request whose access is being evaluated.auth value may be null, so authorization logic must handle unauthenticated requests safely.import NextAuth from "next-auth"
export const { auth, handlers } = NextAuth({
callbacks: {
authorized: async ({ auth }) => {
return !!auth
},
},
})Allows requests from authenticated users and rejects unauthenticated ones.
Require a signed-in session before allowing a page request.
Inspect HTTP methods or request URLs to apply different access rules.
Return a JSON error with a chosen status for unauthorized API calls.
authorized callback run, and what can it return?The authorized callback is invoked when Middleware must authorize a request. It receives auth and request; returning a truthy authorization result permits the request, while a custom NextResponse can implement explicit handling.
Follow-up: How would you return an API error instead of redirecting? Return NextResponse.json(...) with an appropriate HTTP status from the callback.
Use the auth parameter to inspect the authenticated user or token. For a simple protected route, return whether auth exists; for more specific rules, inspect its properties before deciding.
Follow-up: How can the request affect authorization? Read method, URL, or other request data from request, then return a boolean or custom response based on those values.
authorized?The callback receives a parameter object containing auth and request. auth represents the current authenticated user or token, while request is the Next.js request being authorized.
Follow-up: What is a useful method-specific policy? Permit a valid token for a POST request and return a 401 JSON response when validation fails.
callbacksMiddlewareNextResponseSessionNextRequest