question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Order in express middleware

See original GitHub issue

Hello,

I currently use apollo-server-express with next.js. I REALLY want to replace apollo-server with graphql-yoga but it does not work.

In graphql-yoga, middlewares are triggered before endpoint and playground createHttpServer next’s router is a catch all that returns 404 if there is no matching route. run As next’s router is triggered before yoga’s endpoints, when I try to reach ‘/graphql’ I get 404.

With apollo-server-express, I don’t have that problem because I have a way to order express middleware applyMiddleware

Could you change middleware order so that endpoint, playground are before middlewares ? Thanks

Here is my code with graphql-yoga :

import next from 'next';
import routes from 'next-routes';

import { GraphQLServer }  from 'graphql-yoga';
import schema from './models/schema';

const nextApp = next();
const handler = routes()
  .add('home', '/', 'Home')
  .getRequestHandler(nextApp);

nextApp.prepare().then(() => {
  const server = new GraphQLServer({ schema }).use(handler);
  server.start({
    endpoint: '/graphql',
    playground: '/graphql',
    getEndpoint: true
  });
});

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Reactions:1
  • Comments:5

github_iconTop GitHub Comments

2reactions
djgrantcommented, Nov 12, 2018

@kevinya Wrap the next handler in a middleware that checks the request is not for the /graphql route.

nextServer.prepare().then(() => {
  graphQLServer.use((req, res, next) => {
    if (req.path.startsWith("/graphql")) return next();
    nextServerHandler(req, res, next);
  });
  graphQLServer
    .start({
      endpoint: '/graphql',
      playground: '/graphql',
      getEndpoint: true
    })
    .then(() => {
      console.log("Next.js app is running on http://localhost:3000");
      console.log("GraphQL API is running on http://localhost:3000/graphql");
    })
    .catch(() => {
      console.error("Server start failed", err);
      process.exit(1);
    });
});
0reactions
heymartinadamscommented, Jun 19, 2019

Just adding this to the pool. Below, working example that combines next and graphql-yoga (along with some integration of Prisma’s newly-released PhotonJS)

// NextJS
const nextJS = require('next')
const nextRoutes = require('next-routes')
// GraphQL Yoga
const { GraphQLServer } = require('graphql-yoga')
// Prisma Photon
const Photon = require('@generated/photon')
// Custom functions
const { resolvers } = require('./server/resolvers')

// Photon
const photon = new Photon.default()

// NextJS
const nextJSApp = nextJS({ dev: process.env.NODE_ENV !== 'production' })
const nextJSRoutes = nextRoutes()
	.add({ pattern: '/', page: '/' })
	.add({ pattern: '/signin', page: '/signin' })
	.getRequestHandler(nextJSApp)

// GraphQL Endpoint
const gqlEndpoint = '/server'

const gqlServer = new GraphQLServer({
	typeDefs: 'server/schema.graphql',
	resolvers,
	context: data => ({ ...data, photon })
})

// Begin NextJS...
nextJSApp.prepare().then(() => {
	// ...check if GraphQL endpoint is pinged...
	gqlServer.use((req, res, next) => {
		if (req.path.startsWith(gqlEndpoint)) return next()
		// ... if not, use NextJS routes.
		nextJSRoutes(req, res, next)
	})

	// Start server.
	gqlServer
		.start(
			{
				endpoint: gqlEndpoint,
				playground: gqlEndpoint,
				subscriptions: gqlEndpoint,
				port: process.env.PORT || 3000
			},
			() => console.log(`\n🚀 GraphQL server ready at http://localhost:4000`)
		)
		.then(httpServer => {
			async function cleanup() {
				console.log(`\n\nDisconnecting...`)
				await photon.disconnect()
				httpServer.close()
				console.log(`\nDone.\n`)
			}
			// process.on('SIGINT', cleanup)
			process.on('SIGTERM', cleanup)
		})
		.catch(err => {
			console.error('Server start failed ', err)
			process.exit(1)
		})
})

Read more comments on GitHub >

github_iconTop Results From Across the Web

Ordering of Express JS Middleware - Stack Overflow
All Express route handlers (whether app.use() , app.get() , app.post() or anything else) are checked for a route match in the order they...
Read more >
Writing middleware for use in Express apps
The order of middleware loading is important: middleware functions that are loaded first are also executed first. If myLogger is loaded after the...
Read more >
Complete Guide to Express Middleware - Reflectoring
Middleware in Express are functions that come into play after the server receives the request and before the response is sent to the...
Read more >
Confused about middleware order in Express : r/node - Reddit
The order is first come first serve. You should also be careful with route parameters, for example with routes defined in order of...
Read more >
Node.js / Express.js - middleware calls order - Dirask
The order is one of the most important things about middleware. The order in which they are written or included in the file...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found