Fastify Adapter
Package: @nauth-toolkit/core
Type: Framework Adapter
import { FastifyAdapter } from '@nauth-toolkit/core';
FastifyAdapter
Constructor
new FastifyAdapter()
No configuration required.
Usage
import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import { NAuth, FastifyAdapter } from '@nauth-toolkit/core';
const fastify = Fastify();
await fastify.register(cookie);
const nauth = await NAuth.create({
config: { /* ... */ },
dataSource,
adapter: new FastifyAdapter(),
});
Hooks
Returned by nauth.middleware:
| Property | Type | Description |
|---|---|---|
clientInfo | onRequestHookHandler | Initializes context, extracts IP/UA |
csrf | onRequestHookHandler | CSRF token validation |
auth | onRequestHookHandler | JWT validation |
tokenDelivery | onSendHookHandler | Cookie token delivery |
Registration
fastify.addHook('onRequest', nauth.middleware.clientInfo);
fastify.addHook('onRequest', nauth.middleware.csrf);
fastify.addHook('onRequest', nauth.middleware.auth);
fastify.addHook('onSend', nauth.middleware.tokenDelivery);
Helpers
Returned by nauth.helpers:
requireAuth()
requireAuth(options?: { csrf?: boolean }): preHandlerHookHandler
Returns 401 if not authenticated. Use as preHandler.
| Option | Type | Default | Description |
|---|---|---|---|
csrf | boolean | true | Validate CSRF token |
public()
public(): preHandlerHookHandler
Marks route as public, bypasses CSRF.
optionalAuth()
optionalAuth(): preHandlerHookHandler
Allows authenticated and anonymous access.
getCurrentUser()
getCurrentUser(): IUser | undefined
Returns authenticated user from context.
tokenDelivery()
tokenDelivery(mode: 'json' | 'cookies'): preHandlerHookHandler
Overrides token delivery mode for route.
skipRecaptcha()
skipRecaptcha(): preHandlerHookHandler
Bypasses reCAPTCHA validation for the route even when globally enabled. Useful for admin routes or internal endpoints.
requireRecaptcha()
requireRecaptcha(): preHandlerHookHandler
Enforces reCAPTCHA validation for the route even when not globally enabled. Use for high-risk operations like password reset or account deletion.
getCurrentSession()
getCurrentSession(): string | number | undefined
Returns the current session ID from AsyncLocalStorage context. Only available after nauth.middleware.auth has run.
getClientInfo()
getClientInfo(): ClientInfo | undefined
Returns the client info object from AsyncLocalStorage context (IP address, user agent, device token, etc.). Only available after nauth.middleware.clientInfo has run.
Route Handler Wrapper
wrapRouteHandler()
nauth.adapter.wrapRouteHandler<T>(
handler: (req: NAuthRequest, res: NAuthResponse) => Promise<T>
): RouteHandlerMethod
Wraps route handler to ensure AsyncLocalStorage context propagation.
Example
fastify.post('/signup', {
preHandler: nauth.helpers.public(),
handler: nauth.adapter.wrapRouteHandler(async (req) => {
return nauth.authService.signup(req.body);
}),
});