Authenticate a request
Protect middleware or server handlers by checking whether the incoming request has a valid Auth.js token.
Auth.js · Function
getToken reads an Auth.js JWT from request cookies or the Authorization header. It returns the decoded payload by default, the raw token when requested, or null when no usable JWT is found.
getToken examines an Auth.js request for a JWT in either its cookies or Authorization header. By default it decodes and returns the token payload; setting raw to true returns the JWT string instead, while an absent or malformed token produces null.
function getToken<R>(params): Promise<R extends true ? string : null | JWT>| Name | Type | Description |
|---|---|---|
req | Request | { headers: Headers | Record<string, string> } | The request containing the JWT in cookies or in the Authorization header. |
cookieName | string (optional) | The cookie name to search when the JWT is stored in a cookie. |
raw | boolean (optional) | When true, return the raw JWT string. |
Promise<R extends true ? string : null | JWT>
import { getToken } from "@auth/core/jwt"
export async function middleware(req: Request) {
const token = await getToken({ req })
if (!token) return new Response("Unauthorized", { status: 401 })
return new Response("OK")
}Reads the Auth.js JWT from the request and rejects requests for which no token is available.
Protect middleware or server handlers by checking whether the incoming request has a valid Auth.js token.
Retrieve custom claims that Auth.js stored in the decoded JWT payload.
Pass a nonstandard cookie name when an application does not use the default JWT cookie name.
getToken takes an Auth.js request and returns a promise containing either the decoded JWT payload or the raw JWT string. It searches both cookies and the Authorization header.
Follow-up: What happens when the request has no usable token? The function returns null, including for malformed percent-encoding in a Bearer value.
Use the raw option set to true when the caller needs the original JWT text rather than its decoded payload. The return type then resolves to a string.
Follow-up: What is the default? Without raw: true, the function resolves to a JWT payload or null.
The function accepts a request object through the req parameter. That request must contain the JWT in cookies or in the Authorization header for retrieval to succeed.
Follow-up: Why should the returned JWT not automatically be sent to another API? The documentation says Auth.js JWTs are intended for the same application that created them.
JWTencodedecodeauth