Guides/Production patterns
Verify sessions in other services
Let an API in another process or language trust who is signed in, with the JWT plugin's tokens and key set.
The problem
An API that runs apart from the auth server, on another host or in another language, does not receive the session cookie, and asking the auth server about every request costs a round trip each time. The JWT plugin signs a short-lived token for the signed-in person. The API checks that token's signature against the auth server's public keys and needs no shared secret for it.
When to use it
- Your data comes from a service of its own: a backend in Python, Go or another language, or a TypeScript API on another host.
- The service keeps its own sessions and wants to exchange the token for one of them.
Not needed when the code runs in the same process as the auth server. There, read the session with auth.api.getSession({ headers }), or check a token with auth.api.verifyJWT.
Setup
Add the JWT plugin
import { entroAuth } from "@entro314labs/entro-auth";
import { jwt } from "@entro314labs/entro-auth/plugins";
export const auth = entroAuth({
baseURL: "https://auth.example.com",
plugins: [
jwt({
jwt: {
expirationTime: "5m",
definePayload: ({ user, session }) => ({
email: user.email,
email_verified: user.emailVerified,
sid: session.id,
}),
},
// only if nothing reads the set-auth-jwt header of /get-session
disableSettingJwtHeader: true,
}),
],
});subis the user's id unless you setgetSubject.issandaudarebaseURLunless you setissuerandaudience.- Without
definePayloadthe whole user object goes into the token. Name the claims your service reads. - Keys are EdDSA (Ed25519) by default. If the library your service verifies with does not take that algorithm, choose another with
jwks.keyPairConfig, for example{ alg: "RS256" }. See Algorithm of the Key Pair.
Send the token from the client
getJwt keeps one token until shortly before it runs out, so a page that calls the API many times asks the auth server once:
import { createAuthClient } from "@entro314labs/entro-auth/client";
import { jwtClient } from "@entro314labs/entro-auth/client/plugins";
export const authClient = createAuthClient({
plugins: [jwtClient()],
});const token = await authClient.getJwt();
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}getJwt answers null when nobody is signed in and throws when the server cannot be asked. Call authClient.forgetJwt() when your API refuses a token. In TanStack Start, the integration package keeps one token for the server render and the browser.
Verify in the service
There are two ways to get the public keys.
Over HTTP. The auth server publishes them at /api/auth/jwks (or the path set with jwks.jwksPath). Cache the key set, and fetch it again when a token names a kid you do not have. With jose:
import { createRemoteJWKSet, jwtVerify } from "jose";
const JWKS = createRemoteJWKSet(new URL("https://auth.example.com/api/auth/jwks"));
export async function verify(token: string) {
const { payload } = await jwtVerify(token, JWKS, {
issuer: "https://auth.example.com",
audience: "https://auth.example.com",
});
return payload; // payload.sub is the user id
}In another language, use a JOSE library that reads a JWK set from a URL, and check the signature, exp, iss and aud.
From a shared database. A service that already connects to the auth server's database can read the jwks table instead: publicKey holds the public JWK as JSON text, with alg beside it. The privateKey column is encrypted unless disablePrivateKeyEncryption is set, and the service has no use for it. See the table's schema.
Pitfalls
- The issuer is
baseURLto the character.https://example.comandhttps://example.com/are two issuers. A service configured with the other form refuses every token. The auth server logs a warning with both values when it refuses a token for its issuer or audience. - A token outlives its session. Signing out or revoking a session does not take back a token already issued; it stays good until
exp. KeepexpirationTimeshort. A service that must stop at once when an account is deleted checks that the user still exists, bysub. A service that exchanges the token for a session of its own can be told when a session ends or an account is deleted with Account Events. See What a token does not tell you. verifyJWTthrows when it cannot read the keys.payloadisnullonly for a token that was checked and refused. Answer a thrown error as an outage of your service (a 503), not as a 401, or an unreachable database signs everybody out.- The
set-auth-jwtheader costs a key read on every/get-session. Turn it off withdisableSettingJwtHeader: trueunless something reads it. - With the OAuth provider or MCP plugin, turn off
/tokenand the header as described in OAuth Provider Mode, so a session token cannot pass for an access token. - Only copy the claims the token carries. A service that fills a missing name from the address and writes it on every sign-in overwrites the name the person set. Whichever side keeps the profile keeps the name.
- Expect several first requests at once. A service that creates its own row for a new account on the first request sees a page fire its queries together. Insert the row if it is missing (insert-or-nothing), then read it, instead of a plain insert that fails for all but one request.
- Two sessions, two sign-outs. When the service keeps its own session, end the service's session first and then the auth server's. Ending the auth server's first leaves the service's sign-out without a session to authorize it. Tell the code that exchanges tokens for service sessions that a sign-out is under way, so it does not open a new one in between.
- Moving from another provider: deploy the issuer first. Put the auth server with its key set live and check it alone (the key set, a token's claims) while the service still trusts the old provider. Switch the service after that, so people already signed in keep working during the change.
Reference
- JWT plugin: options, key rotation, remote signing
- Account Events:
session.endedanduser.deletedfor another service - Bearer plugin: Bearer tokens in place of cookies, for clients and APIs that cannot use cookies