François Romain
François Romain

Reputation: 14393

express-jwt and express-graphql: error TS2339: Property 'user' does not exist on type 'Request'

I try to make express-jwt and graphql work together in typescript.

import * as express from 'express'
import * as expressGraphql from 'express-graphql'
import * as expressJwt from 'express-jwt'

import schema from './api/schemas'
import rootValue from './api/resolvers'

const app = express()

app.use(
  expressJwt({
    credentialsRequired: false,
    secret: process.env.JWT_SECRET
  })
)

app.use(
  '/',
  expressGraphql((req, res, graphQLParams) => ({
    schema,
    rootValue,
    context: {
      user: req.user
    }
  }))
)

I imported the relative typings @types/express, @types/express-graphql and @types/express-jwt.

There is a typescript error:

error TS2339: Property 'user' does not exist on type 'Request'

user is added on the request object by express-jwt.

How can I fix that?

Upvotes: 2

Views: 524

Answers (1)

François Romain
François Romain

Reputation: 14393

extends Express Request with one property

interface AuthRequest extends express.Request {
  user?: string
}

app.use(
  '/',
  expressGraphql((req: AuthRequest, res, graphQLParams) => ({
    schema,
    rootValue,
    context: {
      user: req.user
    }
  }))
)

Upvotes: 1

Related Questions