'NextJS: How to handle multiple dynamic routes at the root

Goal: I would like to achieve github style routing, where abcd in github.com/abcd could resolve to a user profile page or a team page.

I currently have a version that sort of works (see below). Unfortunately I am occasionally getting a white page flash when navigating between 2 dynamic routes.

My server file looks like:

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

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const nextApp = next({
  dev,
});
const nextHandle = nextApp.getRequestHandler();

const STATIC_ROUTES = [
  '/about',
  '/news',
  '/static',
];

const DYNAMIC_ROUTE_MAP = {
  user: '/[user]',
  team: '/teams/[team]',
};

nextApp.prepare().then(() => {
  const server = express();

  server.get('*', async (req, res) => {
    // pass through next routes
    if (req.url.indexOf('/_next') === 0) {
      return nextHandle(req, res);
    }

    // pass through static routes
    if (
      req.url === '/' ||
      STATIC_ROUTES.map(route => req.url.indexOf(route) === 0).reduce(
        (prev, curr) => prev || curr,
      )
    ) {
      return nextHandle(req, res);
    }

    // try to resolve the route
    // if successful resolves to an object:
    // { type: 'user' | 'team' }
    const resolvedRoute = await resolveRoute(req.url);
    if (!resolvedRoute || !resolvedRoute.type) {
      console.error('🛑 Unable to resolve route...');
      return nextHandle(req, res);
    }

    // set query
    const { pathname } = parse(req.url);
    const paths = pathname.split('/').filter(path => path.length > 0);
    const query = {
      [resolvedRoute.type]: paths.length > 0 ? paths[0] : null,
    };

    // render route
    return nextApp.render(
      req,
      res,
      DYNAMIC_ROUTE_MAP[resolvedRoute.type],
      query,
    );
  });

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

I'm wondering if there is a better way to handle this or if I need to move away from NextJS.



Solution 1:[1]

Next.JS has built in dynamic routing, which shouldn't require you to create a custom server.js file. If you want full compatibility with Next.JS you should use it's dynamic routing instead.

To create a dynamic route in Next.JS you can create pages with names surrounded in square brackets e.g. /pages/[username].js. This will match all routes on your base domain, so you can set up the example you mentioned with github e.g. http://yourwebsite.com/csbarnes and http://yourwebsite.com/anotherusername.

In the example above you can grab the username in your Next.JS page from the query parameter in getInitialProps just in the same way as you would with any query string parameters:

static getInitialProps({query}) {
  console.log(query.username); // the param name is the part in [] in your filename
  return {query}; // you can now access this as this.props.query in your page
}

Next.JS always matches static routes before dynamic routes meaning your /pages/ directory can look like this:

pages/index.js       -> (will match http://yourwebsite.com)
pages/about.js       -> (will match http://yourwebsite.com/about)
pages/contact.js     -> (will match http://yourwebsite.com/contact)
pages/[username].js  -> (will match http://yourwebsite.com/[anything_else])

Multiple segments

You can have multiple segment dynamic routes, such as http://website.com/[username]/[repo] using folders in your pages directory:

pages/[username].js      -> (matches http://yourwebsite.com/[username])
pages/[username]/[repo]  -> (matches http://yourwebsite.com/[username]/[repo])

In this instance your query object will contain 2 params: { username: ..., repo: ...}.

Route "prefixes"

You can have multiple dynamic routes with different "prefixes" if you wish by creating folders in your pages directory. Here is an example folder structure with a website.com/[username] route and a website.com/teams/[team] route:

multiple dynamic routes

Dynamic number of different segments

You can also have dynamic routes with any number of dynamic segments. To do this you need to use an ellipsis ("...") in your dynamic route file name:

/pages/[...userDetails].js  -> (will match http://website.com/[username]/[repo]/[etc]/[etc]/[forever]) 

In this instance your this.props.userDetails variable will return an array rather than a string.

Solution 2:[2]

One addition regarding usage of SSR and SSG pages and you need to differentiate those with dynamic URLs by adding the '-ssr' prefix to an URL.

For example, you need some pages to be SSR, then you can create under the pages an ssr folder where you could put the page [[...path]].js with getServerSideProps. Then you could use such rewrite in the next.config.js under async rewrites() {:

{
    source: '/:path*/:key-ssr', destination: '/ssr/:path*/:key-ssr'
}

that covers such URLs:

  • /page-ssr
  • /en/page1/page-ssr
  • /en/page1/page2/page-ssr
  • /en/page1/page2/page3/page-ssr

etc.

Solution 3:[3]

You can't have two different types of dynamic routes at one route. The browser has no way of differentiating between a and b, or in your case a username and a team name.

What you can do is have subroutes, lets say /users and /teams, that have their own respective dynamic routes.

The folder structure for that in NextJS would look like this:

/pages/users/[name].js
/pages/teams/[name].js

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 aleks korovin
Solution 3 Wizard