Authentication
Protect routes with token-based authentication using cookies, Bearer tokens or both authentication methods.
Authentication middleware
LykosJS provides the AuthMiddleware class to authenticate incoming requests using access tokens. It supports cookie-based authentication, Bearer token authentication, or both methods through a configurable authentication mode.
The middleware extracts the token, passes it to your custom verification function, and attaches the verified user and authentication token to the request context.
Import
1import {2 AuthMiddleware,3 type AuthMiddlewareOptions,4 type AuthMode,5 type TokenVerifier,6 type VerifiedUser,7} from 'lykosjs'Create an authentication middleware
1import { AuthMiddleware } from 'lykosjs'2 3const auth = new AuthMiddleware(4 async (token) => {5 const payload = await verifyAccessToken(token)6 7 if (!payload) {8 return null9 }10 11 return {12 id: payload.sub,13 email: payload.email,14 role: payload.role,15 }16 },17)18 19app.use(auth.middleware)The constructor accepts a token verification function and an optional configuration object. If no configuration is provided, the middleware uses both mode and the cookie name token.
auth.middleware is a ready-to-use middleware function with the signature (ctx, reply, next). It is defined as an instance property, so you can pass it directly to app.use(), to a route or to a route group without binding it.
Authentication modes
The mode option determines where the middleware looks for the authentication token. Three modes are supported: cookie, bearer and both. Any other value is not a valid mode.
1type AuthMode = 'cookie' | 'bearer' | 'both'2 3type AuthMiddlewareOptions =4 | { mode: 'cookie'; cookieName: string }5 | { mode: 'bearer' }6 | { mode: 'both'; cookieName: string }The options type is a discriminated union. The cookieName property is required in cookie and both mode, and it is not accepted in bearer mode.
Cookie authentication
Use cookie mode when the client sends its authentication token through a named cookie.
1const auth = new AuthMiddleware(2 verifyAccessToken,3 {4 mode: 'cookie',5 cookieName: 'access_token',6 },7)8 9app.use(auth.middleware)The middleware reads the cookie using CookieManager.fromRequest() and retrieves its value using the configured cookie name.
In this mode the Authorization header is ignored completely. If the cookie is missing, or its value is empty, the request is rejected as unauthenticated.
Bearer authentication
Use bearer mode when clients send their token through the HTTP Authorization header.
1const auth = new AuthMiddleware(2 verifyAccessToken,3 {4 mode: 'bearer',5 },6)7 8app.use(auth.middleware)The expected header format is:
1Authorization: Bearer your-access-tokenThe middleware matches the Bearer scheme without case sensitivity and requires a non-whitespace token after at least one whitespace character. If an Authorization header exists but does not match the expected format, authentication fails.
1// Accepted2Authorization: Bearer abc1233Authorization: bearer abc1234Authorization: BEARER abc1235 6// Rejected7Authorization: abc1238Authorization: Basic abc1239Authorization: Bearer10Authorization: Bearer abc 123In this mode cookies are never read. A request without an Authorization header is rejected as unauthenticated.
Support cookies and Bearer tokens
Use both mode to support both authentication methods. The middleware checks the Authorization header first and falls back to the configured cookie only when the header is absent.
1const auth = new AuthMiddleware(2 verifyAccessToken,3 {4 mode: 'both',5 cookieName: 'access_token',6 },7)8 9app.use(auth.middleware)This is also the default mode. Omitting the options object is equivalent to the following configuration:
1new AuthMiddleware(verifyAccessToken, {2 mode: 'both',3 cookieName: 'token',4})Token extraction summary
- cookie — reads only the configured cookie. The Authorization header is ignored.
- bearer — reads only the Authorization header. It must use the Bearer format. Cookies are ignored.
- both — uses the Authorization header when it is present (and fails if it is not a valid Bearer header). Reads the configured cookie only when the header is absent.
Configure the token verifier
The token verifier is a function responsible for validating the token and returning the authenticated user. It can be synchronous or asynchronous.
1import type { TokenVerifier } from 'lykosjs'2 3const verifyToken: TokenVerifier = async (token) => {4 const payload = await verifyAccessToken(token)5 6 if (!payload) {7 return null8 }9 10 return {11 id: payload.sub,12 email: payload.email,13 role: payload.role,14 }15}The verifier receives the extracted token as a string. It must return either a VerifiedUser object or null. Returning null indicates that the token could not be authenticated.
1type TokenVerifier = (2 token: string,3) => Promise<VerifiedUser | null> | VerifiedUser | nullIf verification throws an error, the middleware logs the verification failure and passes the error to the framework's ErrorHandler, whose result is returned as the response.
Verified user type
The VerifiedUser interface describes the user object returned by the verifier. It requires an id string and allows additional properties.
1export interface VerifiedUser {2 id: string3 [key: string]: unknown4}You can return additional properties such as email, role, permissions or other application-specific information.
1const verifyToken: TokenVerifier = async (token) => {2 const payload = await verifyAccessToken(token)3 4 if (!payload) return null5 6 return {7 id: payload.sub,8 email: payload.email,9 role: payload.role,10 permissions: payload.permissions,11 }12}Access the authenticated user
After successful verification, the middleware attaches the authenticated user to ctx.user. You can access this information in downstream middleware and route handlers.
1app.GET('/profile', async (ctx, reply) => {2 const user = ctx.user3 4 return reply.OK({5 id: user?.id,6 email: user?.email,7 role: user?.role,8 })9})The middleware also stores the verified token in ctx.auth.token.
1const authenticatedUser = ctx.user2const accessToken = ctx.auth?.tokenOnce both values are set, the middleware calls next() and the request continues to the next middleware or route handler.
Register globally
Register the middleware with app.use() to authenticate every request handled after it.
1const auth = new AuthMiddleware(verifyAccessToken)2 3app.use(auth.middleware)Protect specific routes
You can attach the authentication middleware to a route instead of registering it globally.
1const auth = new AuthMiddleware(2 verifyAccessToken,3 { mode: 'bearer' },4)5 6app.GET('/profile', getProfile, auth.middleware)7 8app.GET('/admin/dashboard', getDashboard, auth.middleware)Protect a group of routes
Use route groups to apply authentication to multiple endpoints under the same prefix.
1const auth = new AuthMiddleware(2 verifyAccessToken,3 { mode: 'cookie', cookieName: 'access_token' },4)5 6app.group(7 '/api/private',8 (privateRoutes) => {9 privateRoutes.GET('/profile', getProfile)10 privateRoutes.GET('/settings', getSettings)11 privateRoutes.GET('/orders', getOrders)12 },13 auth.middleware,14)Authentication failures
The middleware handles the following authentication scenarios:
- Missing or malformed token — Returns an Unauthorized response with the message
Authentication token is missing or invalid.This happens when no token is found in the configured source, when the token is empty, or when the Authorization header does not use the Bearer format. - Invalid or expired token — When the verifier returns
null, the middleware returns an Unauthorized response with the messageToken is invalid or expired. - Verification exception — Logs the error and delegates its handling to
ErrorHandler.handle().
Both Unauthorized responses use the same body shape:
1{2 "success": false,3 "message": "Authentication token is missing or invalid."4}5 6{7 "success": false,8 "message": "Token is invalid or expired."9}The verifier is only called when a token has been extracted. A request that fails at the extraction step never reaches your verification function.
Common mistakes
1// Incorrect: missing required user ID2const verifyToken: TokenVerifier = async (token) => {3 return {4 email: 'user@example.com',5 }6}7 8// Correct: VerifiedUser requires an id9const verifyToken: TokenVerifier = async (token) => {10 return {11 id: 'user-123',12 email: 'user@example.com',13 }14}15 16// Incorrect: returning an invalid verification result17const invalidVerifier: TokenVerifier = async (token) => {18 return false19}20 21// Correct: return null when verification fails22const validVerifier: TokenVerifier = async (token) => {23 return null24}25 26// Incorrect: cookie and both modes require cookieName27const auth = new AuthMiddleware(verifyAccessToken, {28 mode: 'cookie',29})30 31// Correct32const auth = new AuthMiddleware(verifyAccessToken, {33 mode: 'cookie',34 cookieName: 'access_token',35})36 37// Incorrect: bearer mode does not use a cookie38const auth = new AuthMiddleware(verifyAccessToken, {39 mode: 'bearer',40 cookieName: 'access_token',41})42 43// Correct44const auth = new AuthMiddleware(verifyAccessToken, {45 mode: 'bearer',46})Only cookie, bearer and both are valid values for mode. TypeScript rejects every other value.