0

I'm trying to make a GraphQL (GraphQL Yoga) api using TypeORM and I'm having a problem on how to check JWT token on every request to validate it and insert the user id on the request object.

My code is the following:

index.ts:

const app = new GraphQLServer({
    schema: mergeSchemas({ schemas }),
    context: ({ req }) => ({
      req,
    }),
  });

  app.express.post('/', addUser);

addUser.ts:

import { Request, Response, NextFunction } from 'express';
import * as jwt from 'jsonwebtoken';
import { refreshTokens } from '../utils/auth';

const addUser = async (req: Request, res: Response, next: NextFunction) => {
  const SECRET = process.env.SECRET;
  const REFRESH_SECRET = process.env.REFRESH_SECRET;

  const token = req.headers['x-token'];
  if (token) {
    try {
      if (SECRET) {
        const id = jwt.verify(token[0], SECRET);
        req.user = id;
      }
    } catch (e) {
      const refreshToken = req.headers['x-refresh-token'];
      if (refreshToken && SECRET && REFRESH_SECRET) {
        const newTokens = await refreshTokens(refreshToken[0], SECRET, REFRESH_SECRET);
        if (newTokens.token && newTokens.refreshToken) {
          res.set('Access-Control-Expose-Headers', 'x-token, x-refresh-token');
          res.set('x-token', newTokens.token);
          res.set('x-refresh-token', newTokens.refreshToken);
        }
        req.user = newTokens.user;
      }
    }
  }
  next();
}

export default addUser;

I've extended the Request object with an interface (not sure if it is being properly loaded).

express.d.ts:

declare namespace Express {
  export interface Request {
    user: any
  }
}

And my tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": [
      "dom",
      "es6",
      "es2017",
      "esnext.asynciterable"
    ],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true
  },
  "exclude": [
    "node_modules"
  ],
  "include": [
    "./src/**/*.tsx",
    "./src/**/*.ts"
  ]
}

But when I try to start the server, the following error appears:

TSError: ⨯ Unable to compile TypeScript:
src/middleware/addUser.ts(14,13): error TS2339: Property 'user' does not exist on type 'Request'.
src/middleware/addUser.ts(25,13): error TS2339: Property 'user' does not exist on type 'Request'.

Have anyone solved this problem, or have any idea on how can I improve this code?

Thank you!

1 Answers1

0

duplicate question of extend-express-request

from what i tried this solution worked best solution