Catch all routing except for /graphql

Viewed 696

I have a node.js server application that uses express and apollo-server-express to server my application. I want to serve my react client using a catch-all routing method, however, I still want to expose the /graphql endpoint. How can I do this so that /graphql doesn't get caught in the rest of my routing? Thanks.

import express from 'express';

const app = express();

app.get('/graphql', (request, response) => {
  // ? not sure what to do here.l
});

app.get('*', (request, response) => {
  response.sendFile('index.html', { root: '.' });
});
1 Answers

You don't have to manually define the /graphql route if you are indeed using the apollo-server-express package which is recommended if you want to combine Apollo with the express middleware. The official documentation actually puts you on the right track. In your specific case, your server setup should look someting like this:

const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');

// Construct a schema, using GraphQL schema language
const typeDefs = gql`
  type Query {
    hello: String
  }
`;

// Provide resolver functions for your schema fields
const resolvers = {
  Query: {
    hello: () => 'Hello world!',
  },
};

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

const app = express();
server.applyMiddleware({ app });

app.get('*', (request, response) => {
  console.log('catch-all hit.');
});

app.listen({ port: 3000 }, () =>
  console.log(` Server ready at http://localhost:3000${server.graphqlPath}`)
);

Just make sure that you define your catch-all route AFTER executing server.applyMiddleware, which sets up the /graphql endpoint for you. That way the /graphql endpoint is hit first and will be used to handle those requests. All the other requests will be handled by the catch-all.

Related