Skip to content
LykosJSLYKOSJS
CreatorDeveloperBenchmarkshomeGet started
v1.0.0
OverviewCORSLoggerAuthenticationMiddleware Pipeline
PREVIOUSLoggerNEXT Middleware Pipeline
© 2026 LykosJS · MIT LicenseBun · TypeScript

© 2026 LykosJS. Released under the MIT License.
Built by Zen Allaham.

DocsGitHubX
DOCS/V1.0.0/MIDDLEWARES
MIDDLEWARES

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

ts
1import {2  AuthMiddleware,3  type AuthMiddlewareOptions,4  type AuthMode,5  type TokenVerifier,6  type VerifiedUser,7} from 'lykosjs'

Create an authentication middleware

ts
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.

ts
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.

ts
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.

ts
1const auth = new AuthMiddleware(2  verifyAccessToken,3  {4    mode: 'bearer',5  },6)7 8app.use(auth.middleware)

The expected header format is:

ts
1Authorization: Bearer your-access-token

The 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.

ts
1// Accepted2Authorization: Bearer abc1233Authorization: bearer abc1234Authorization: BEARER abc1235 6// Rejected7Authorization: abc1238Authorization: Basic abc1239Authorization: Bearer10Authorization: Bearer abc 123

In 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.

ts
1const auth = new AuthMiddleware(2  verifyAccessToken,3  {4    mode: 'both',5    cookieName: 'access_token',6  },7)8 9app.use(auth.middleware)
Token extraction priority
In both mode, an existing Authorization header takes priority. If that header is malformed or contains an invalid Bearer format, the middleware does not fall back to the cookie.

This is also the default mode. Omitting the options object is equivalent to the following configuration:

ts
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.

ts
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.

ts
1type TokenVerifier = (2  token: string,3) => Promise<VerifiedUser | null> | VerifiedUser | null

If 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.

ts
1export interface VerifiedUser {2  id: string3  [key: string]: unknown4}

You can return additional properties such as email, role, permissions or other application-specific information.

ts
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.

ts
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.

ts
1const authenticatedUser = ctx.user2const accessToken = ctx.auth?.token

Once both values are set, the middleware calls next() and the request continues to the next middleware or route handler.

Authentication context
ctx.user and ctx.auth are populated only after successful token verification by this middleware. Their availability in a route depends on that route executing the authentication middleware first.

Register globally

Register the middleware with app.use() to authenticate every request handled after it.

ts
1const auth = new AuthMiddleware(verifyAccessToken)2 3app.use(auth.middleware)
Global registration protects every route
A globally registered authentication middleware rejects every request without a valid token, including public routes such as login or registration. For applications with public endpoints, attach the middleware to specific routes or groups instead.

Protect specific routes

You can attach the authentication middleware to a route instead of registering it globally.

ts
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.

ts
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 message Token is invalid or expired.
  • Verification exception — Logs the error and delegates its handling to ErrorHandler.handle().

Both Unauthorized responses use the same body shape:

ts
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

ts
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.

Security recommendations

Verify tokens securely
Never trust a token simply because it exists. Your verification function should validate its signature, expiration and any application-specific claims required by your authentication policy.
Authentication is not authorization
Authentication confirms the identity of the requester. It does not automatically check whether the user has permission to access a resource. Implement authorization checks separately for roles, permissions and protected operations.
Cookies are sent automatically by browsers
When you authenticate with cookies, browsers attach them to requests automatically. Configure your cookies with appropriate attributes (such as HttpOnly, Secure and SameSite) and protect state-changing routes against cross-site request forgery. Bearer tokens sent explicitly in a header are not attached automatically by the browser.