#nextjs#apollo#expressjs#graphql

Setup NextJS alongside with Apollo Server and ExpressJS

Following is a snippet to setup NextJS alongside with Apollo Server and ExpressJS

const Express = require('express');
const next = require('next');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const dev = process.env.NODE_DEV !== 'production'; //true false
const nextApp = next({dev});
const handle = nextApp.getRequestHandler(); //part of next config

nextApp.prepare().then(() => {

  // Express =============================================
  const express = Express();
  express.use(bodyParser.json());
  express.use(bodyParser.urlencoded({extended: true}));

  // Apollo ==============================================
  const {ApolloServer} = require('apollo-server-express');

  const typeDefs = require('./schemas');
  const resolvers = require('./resolvers');

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

  // Apollo & Express combination ========================
  express.all('*', (req, res, next) => {
    if (req.url === apolloServer.graphqlPath) {
      return next();
    }

    return handle(req, res); // for all the react stuff
  });

  apolloServer.applyMiddleware({
    app: express,
  });

  // Other things ========================================
  express.listen({port}, () => {
        console.log(
            `🚀 Apollo Server ready at http://localhost:${port}${apolloServer.graphqlPath}`);
        console.log(`🚀 Next JS App ready at http://localhost:${port}`);
      },
  );
});

Hope it helps!

An Tran

An Tran

A passionate web developer, self-learner and music lover.

Read More