Search code examples
typescriptnamespacesfastify

Property 'X' does not exist on type 'FastifyContext<unknown>'


I want to add the token: string field to the FastifyContext interface. For this purpose I have created the following file structure:

projectDir
|__src
|  |__@types
|  |  |__fastify
|  |  |  |__index.d.ts
|  |__api
|  |  |__authHook.ts
|__tsconfig.json

Content of src/@types/fatify/index.d.ts:

declare module 'fastify' {
    export interface FastifyContext<ContextConfig>{
        token: string
    }
}

Content of src/api/authHook.ts

import {FastifyRequest, FastifyReply} from "fastify";


export default async function authHook(request: FastifyRequest, reply: FastifyReply): Promise<void>{
    // Some logic 
    const token = "example_token" // some result from logic 
    request.context.token = token;
}

Content of tsconfig.json:

{
  "compilerOptions": {
     ...
     "typeRoots": ["src/@types"],
     ...
  }
}

But when I run the code I get the following error:

Property 'token' does not exist on type 'FastifyContext<unknown>'.

What did I do wrong?


Solution

  • import { onRequestHookHandler } from "fastify";
    
    declare module "fastify" {
      export interface FastifyRequestContext {
        token: string;
      }
    }
    
    const authHook: onRequestHookHandler = async function (request, reply) {
      const token = "example_token";
      request.context.token = token;
    };
    
    export default authHook;