How can you handle trailing slashes in next.js routes?

UPDATE: If you are using next export than you can solve the issue by adding exportTrailingSlash to your next.config.js

As of this writing, there seems to be no way to solve this issue without defining your own custom server.

Previous answer:

You must create a new file blog.js shown bellow:

enter image description here

With the following server.js

const express = require('express')
const next = require('next')

const PORT = process.env.PORT || 3000;

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()

app
  .prepare()
  .then(() => {
    const server = express()

    server.get('/blog', (req, res) => {
      const actualPage = '/blog'
     // const queryParams = { title: req.params.id }
      app.render(req, res, '/blog', {})
    })
    server.get('/blog/:id', (req, res) => {
      const actualPage = '/blog/[id]'
      const queryParams = { title: req.params.id }
      app.render(req, res, actualPage, queryParams)
    })

    server.get('*', (req, res) => {
      return handle(req, res)
    })

    server.listen(PORT, err => {
      if (err) throw err
      console.log(`> Ready on http://localhost:${PORT}`)
    })
  })
  .catch(ex => {
    console.error(ex.stack)
    process.exit(1)
  })

node server.js should start your server and you would have the mapping that you need.

Note, blog/index.js is not used in this example.


There is an option with Next.js 9.5 and up.

In next.config.js, add the trailingSlash config:

module.exports = {
  trailingSlash: true,
}

Source: Trailing Slash

Tags:

Next.Js