Skip to main content
Rather than calling 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 the auth property your middleware attaches:
This gives you full type-safety when accessing req.auth.user.id or req.auth.wallet.address inside route handlers.

Express middleware

The following authMiddleware 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

Apply authMiddleware to any route that requires authentication:

Fastify preHandler

In Fastify, use a preHandler 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 uses CanActivate. The guard runs before the route handler and throws UnauthorizedException if the token is invalid:

Protected NestJS routes

Apply SocketFiGuard with the @UseGuards() decorator at the controller or method level:
To protect all routes in your entire application, register SocketFiGuard as a global guard in your AppModule:

Accessing user and wallet info in handlers

Regardless of framework, once middleware attaches the auth object to the request, your handlers can read the verified identity without any additional SDK calls:
Never skip the middleware on routes that access user data or perform wallet operations. A missing Authorization header is not the same as an unauthenticated user — always handle the !token case explicitly and return a 401 before calling verifyAuth().