NextJS, ReactJS

How Configure Sub-Routes in NextJS

For sub-routes like guides/post-slug to work, 3 pieces need to be in place:

1. Files Placement:

NextJS will automatically treats every JavaScript file under /pages as part of valid routes. Therefore, to avoid navigating to components nested under /pages/guides, we define a route in server.js to route all requests under /pages/guides/[blah-title] to the template /pages/guides/Post/Post.js.

Also, when /pages/guide is a path instead of a JavaScript file, NextJS will look for the index.js under this path to render as the page template.

As a result, components under guides can be structured as such:

- pages/
  |- guides/      <-- the name of which is part of URL
    |- index.js          <-- the template to render for URL /guides
    |- Post/             <-- which is a component, and its name is not part of URL
      |- Post.js
      |- Post.less
    |- AnotherComponent/
      |- ...
      |- ...

2. Server Side Setup:

  • /guides/:slug is the URL
  • /guides/Post/Post is the template PATH
// server.js
server.get('/guides/:slug', (req, res) => {
  app.render(req, res, '/guides/Post/Post', { slug: req.params.slug });
});

3. Client Side <Link />s:

  • as={} is the URL
  • href={} is the template PATH
<Link
  as={`/guides/${post.slug}`}
  href={`/guides/Post/Post?slug=${post.slug}`}
  >
  Post Title
</Link>

Don’t mix up the URL and the PATH, and you’ll be good. 😀

Standard

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.