Ad

Unable To Retrieve Value Added To Req Object Via Middleware

I have my server configured thus:

import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { typeDefs, resolvers } from './schema';
import playgroundSettings from './playground.json';
import isAuth from './middleware/isAuth';


// GraphQL: Schema
const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: {
    endpoint: '/blog', /* populates the playground endpoint box below the tab-strip. */
    settings: playgroundSettings,
  },
});

// Express: Initialize
const app = express();
// Middleware: isAuth
app.use(isAuth);
// Middleware: GraphQL route
server.applyMiddleware({
  app,
  path: '/',
});
// Express: Listener
app.listen(process.env.GRAPH_BLOG_PORT, () => {
  console.log(`Server started on port: ${process.env.GRAPH_BLOG_PORT}`);
});

// Exports
export default app;

This is a GraphQL implementation using Apollo Server 2.0 and ExpressJS. However, as you can see, I'm using a custom middleware to perform some authorization tasks before hitting the GraphQL route. This middleware is named isAuth.js and gets called and executed as expected. However, I'm somehow unable to retrieve the properties this middleware adds to my req object from the resolver. The middleware looks like this:

// isAuth.js
import jwt from 'jsonwebtoken';

module.exports = (req, res, next) => {
  let decodedToken;
  const authHeader = req.get('Authorization');
  if (!authHeader) {
    req.isAuth = false;
    return next();
  }
  const token = authHeader.split(' ')[1];
  if (!token || token === '') {
    req.isAuth = false;
    return next();
  }
  try {
    decodedToken = jwt.verify(token, process.env.GRAPH_BLOG_JWT_SECRET);
  } catch (err) {
    req.isAuth = false;
    return next();
  }
  if (!decodedToken) {
    req.isAuth = false;
    return next();
  }
  req.isAuth = true;
  req._id = decodedToken._id;
  return next();
};

And when I do a console.log(req); in my resolver, I expect properties like isAuth and _id, but get the following instead:

{ _extensionStack:
   GraphQLExtensionStack {
     extensions: [ [FormatErrorExtension], [CacheControlExtension] ] } }

What's going on?

Ad

Answer

You need to add the context line as shown below:

const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: {
    endpoint: '/blog', /* populates the playground endpoint box below the tab-strip. */
   settings: playgroundSettings,
 },
 context: ({ req, res }) => ({ req, res })
});
Ad
source: stackoverflow.com
Ad