How Can I Pass the Auth Middleware to the Apollo GraphQL Server

How Can I Pass the Auth Middleware to the Apollo GraphQL Server


1

My App.js

const mongoose = require('mongoose');
const dotenv = require('dotenv');
const { ApolloServer } = require('apollo-server');
const { startStandaloneServer } = require('@apollo/server/standalone');
const typeDefs = require('./apolloGraphql/schema');
const resolvers = require('./apolloGraphql/resolvers');
const auth = require('./Middleware/Auth');

dotenv.config({ path: './config/.env' });

const server = new ApolloServer({
  typeDefs,
  resolvers,
});

mongoose
  .connect(process.env.MONGOURI)
  .then((result) => {
    return server.listen(process.env.PORT, (req, res, next) => {
      console.log(`Server is Listening at PORT ${process.env.PORT}`);
    });
  })
  .then((res) => {
    return console.log(`Server is Running at ${res.url}`);
  })
  .catch((err) => {
    console.log(err);
  });

My Auth Middleware

const jwt = require('jsonwebtoken');

module.exports = (req, res, next) => {
  try {
    const authHeader = req.get('Authorization');
    if (!authHeader) {
      const error = new Error('Not Authorized');
      error.status = 500;
      throw error;
    }
    const token = authHeader.split(' ')[1];
    const decodedToken = jwt.verify(token, process.env.JWT_SECRET);
    if (!decodedToken) {
      const error = new Error('Not Authorized');
      error.status = 500;
      throw error;
    }
    req.userId = decodedToken.userId;
    next();
  } catch (err) {
    console.log(err);
    next(err);
  }
};

How Can I Pass this Middleware to this Apollo Server Like Rest API. I am New To Graphql

I have Tried to Solve this Issue Just Like Rest API and Referred Some Project and Documentation but I Failed to Solved this. I am also Eager to Know is there any Change in the Packages

1

  • This is done via the context function

    – Michel Floyd

    Apr 11 at 16:07

1 Answer
1


0

To pass your middleware to Apollo Server you would need to use Apollo’s expressMiddleware, create an express server add your middlewares and then and pass Apollo’s middleware to it.

This is the example from Apollo’s site (slightly modified) where they modify express middleware.

import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import express from 'express';
import http from 'http';
import cors from 'cors';
import bodyParser from 'body-parser';
import { typeDefs, resolvers } from './schema';

const app = express();

const httpServer = http.createServer(app);


const server = new ApolloServer({
  typeDefs,
  resolvers,
});
await server.start();

// Here you set up Express middleware 
app.use(
  '/',
  cors(),
  bodyParser.json({ limit: '50mb' }),
  // You can add your custom middleware here
  expressMiddleware(server, {
    // You can also process the req and res objects and pass data to your resolvers
    context: async ({ req }) => ({ token: req.headers.token }),
  }),
);

await new Promise((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at https://localhost:4000/`);

Take into account that you probably don’t want an all or nothing middleware for authentication in express, since it will protect the entire graphql endpoint. It could be Okay as long as your log in is done outside of GraphQL (as in a REST endpoint for login).

You can see how to implement authentication logic in Apollo here



Leave a Reply

Your email address will not be published. Required fields are marked *