verifyAuth() directly inside every route handler, the recommended pattern is to extract the verification logic into reusable middleware. This keeps your route handlers focused on business logic and ensures that no protected route accidentally skips token verification. The examples below show how to build auth middleware for Express, Fastify, and NestJS, including how to attach the verified user and wallet to the request object so downstream handlers can use them without re-verifying.
TypeScript: extending the request type
Before writing middleware, extend the framework’s request type so TypeScript knows about theauth property your middleware attaches:
req.auth.user.id or req.auth.wallet.address inside route handlers.
Express middleware
The followingauthMiddleware function reads the token from the Authorization header, calls verifyAuth(), and either attaches the result to req.auth and calls next(), or responds immediately with a 401:
Protected Express routes
ApplyauthMiddleware to any route that requires authentication:
Fastify preHandler
In Fastify, use apreHandler hook to run verification before each request reaches its handler. You can register it globally or on a specific route:
Protected Fastify routes
If you only want to protect specific routes rather than every route, register the preHandler at the route level instead of with
addHook: fastify.get('/protected', { preHandler: authPreHandler }, handler).NestJS Guard
In NestJS, implement authentication as a Guard that usesCanActivate. The guard runs before the route handler and throws UnauthorizedException if the token is invalid:
Protected NestJS routes
ApplySocketFiGuard with the @UseGuards() decorator at the controller or method level:
SocketFiGuard as a global guard in your AppModule:
Accessing user and wallet info in handlers
Regardless of framework, once middleware attaches theauth object to the request, your handlers can read the verified identity without any additional SDK calls: