Centralizing Routing

Robin Millette edited this page Apr 30, 2018 · 8 revisions

Starting with Next.js 6, these instructions are obsolete.

When developing a Next.js app that will be statically exported for production, you'll likely find yourself hitting an issue with Next.js' current architecture, which separates the routes that are accessible when statically exported and the routes that are accessible when running your development server. Unless you're happy to build and export the entire project each time you make a change you'd like to see, you're likely to be frustrated by this separation.

One solution to this issue is to make a routes module and consume it by both the development server and by the static export. Here's an example:

routes.js:

module.exports = () => {
  return {
    '/': { page: '/' },
    '/404': { page: '/404' },
    '/about': { page: '/about' },
    ...
  }
}

server.js:

const express = require('express');
const next = require('next');
const { parse } = require('url');

const dev = process.env.NODE_ENV !== 'production';
const PORT = process.env.PORT || 3000;

const app = next({dir: '.', dev });
const handle = app.getRequestHandler();

const getRoutes = require('./routes');

const routes = getRoutes();
app.prepare().then(() => {
  const server = express();
  server.get('*', (req, res) => {
    const parsedUrl = parse(req.url, true);
    const { pathname, query = {} } = parsedUrl;
    const route = routes[pathname];
    if (route) {
      return app.render(req, res, route.page, query);
    }
    return handle(req, res);
  });

  server.listen(PORT, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${PORT}`);
  });
});

and finally, next.config.js:

const getRoutes = require('./routes');

module.exports = {
  exportPathMap: getRoutes
};
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Press h to open a hovercard with more details.