Skip to content

How to properly decorate request in TypeScript #5100

Closed Answered by metcoder95
awais-shafiq asked this question in Q&A
Discussion options

You must be logged in to vote

You need to do the augmentation on the same place as the application code, otherwise, it rewrites the module type definition, leading to errors. A working example might be:

import { fastify } from 'fastify';

declare module 'fastify' {
  interface FastifyRequest {
    user: {
      id: number;
    };
  }
}

const server = fastify();

server.decorateRequest('user', null);

server.addHook('preHandler', (request, _reply, done) => {
  request.user = { id: 10001 };
  done();
});

server.get('/', (request, reply) => {
  console.log(request.user);
  reply.code(200).send({ success: true });
});

Replies: 5 comments 1 reply

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
1 reply
@metcoder95
Comment options

Answer selected by awais-shafiq
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants