Issue an Auth.js JWT
Create the session token Auth.js will issue after authentication.
Auth.js · Function
encode asynchronously issues an Auth.js JWT from JWTEncodeParams. By default, the JWT is encrypted with A256CBC-HS512 using a key derived from the configured or supplied secret.
encode asynchronously creates an Auth.js JWT from the supplied encoding parameters. Unless customized, Auth.js encrypts the JWT with A256CBC-HS512, deriving the encryption key from the provided secret.
function encode<Payload>(params): Promise<string>| Name | Type | Description |
|---|---|---|
params | JWTEncodeParams<Payload> | Encoding options, including the token payload and secret used for JWT processing. |
Promise<string> containing the issued JWT.
encode produces an Auth.js JWT string asynchronously.JWTEncodeParams object parameterized by the payload type.import { encode } from "@auth/core/jwt"
const token = await encode({
token: { sub: "user_123", role: "admin" },
secret: process.env.AUTH_SECRET!,
})
console.log(token)Creates an Auth.js JWT from a payload and secret, then prints the resulting encoded token.
Create the session token Auth.js will issue after authentication.
Use a custom payload type for application-specific claims.
Replace the default JWT serialization or protection behavior.
encode accept and return?encode accepts JWTEncodeParams<Payload> and returns Promise<string>. Its purpose is to issue an Auth.js JWT.
Follow-up: What is the default protection mode? The resulting JWT is encrypted with A256CBC-HS512 unless the encoding behavior is overridden.
Payload type parameter play?The generic payload type defaults to JWT, allowing callers to describe a more specific payload type when invoking the function. The encoded result remains a promise of a string.
Follow-up: How would you preserve type safety for application claims? Supply a payload type that includes those claims and pass a matching token object in the parameters.
encode?The function is an overridable encoding hook for Auth.js-issued JWTs. Replacing it lets an application control how those JWTs are encoded.
Follow-up: What should be checked when overriding it? The replacement must honor the expected parameters and produce an awaitable string compatible with Auth.js.
JWTEncodeParamsJWTdecodeA256CBC-HS512AUTH_SECRET