8000 How to properly decorate request in TypeScript · fastify fastify · Discussion #5100 · GitHub
[go: up one dir, main page]

Skip to content
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: 8 comments 2 replies

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
F440
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
1 reply
@jbeckton
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
6 participants
0