0

I have this declaration file in the project's root called fastify.d.ts:

import { auth } from "firebase-admin";

declare module 'fastify' {
  interface FastifyRequest {
    user: auth.DecodedIdToken
  }
}

And I've been using to set a user to an incoming request such as:

export default async function mustBeLoggedIn(
  req: FastifyRequest,
  reply: FastifyReply
) {
  try {
    const token = req.headers.authorization?.replace("Bearer ", "") ?? "";

    const result = await auth.verifyIdToken(token);

    req.user = result;
  } catch (err) {
    reply.status(401).send({
      error: "You must be logged in to access this resource",
    });
  }
}

And I get the error: middlewares/mustBeLoggedIn.ts(13,9): error TS2339: Property 'user' does not exist on type 'FastifyRequest<RouteGenericInterface, Server, IncomingMessage>'.

Current tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
  },
  "include": ["**/*.ts", "**/*.d.ts"],
  "exclude": ["node_modules"]
}

How can I fix this? Thanks!

Stan Loona
  • 615
  • 9
  • 18

2 Answers2

2

Try import FastifyRequest, like this:

import FastifyRequest from "fastify";
import { auth } from "firebase-admin";

declare module 'fastify' {
  interface FastifyRequest {
    user: auth.DecodedIdToken
  }
}
-1

Add

  "ts-node": {  "files": true },

to root level of tsconfig.json.

https://stackoverflow.com/a/68488480/6398044

Daniel
  • 7,684
  • 7
  • 52
  • 76