Search code examples
http-redirectnext.jsnetlify

Trailing slash for Next.js on Netlify not working


We have a Next.js site on Netlify with static and server-rendered pages. We have links like https://example.com/locations/berlin and we would like to have them to always end with a trailing slash like https://example.com/locations/berlin/. To achieve this, we use the trailingSlash: true option of Next.js which is working fine locally.

The problem occurs when we deploy our site to Netlify. The pages are always redirected to the url without trailing slash, like https://example.com/locations/berlin with status code 301. We already enabled Pretty URLs in the Netlify Build Settings but that makes no difference.

When I understand it correctly, with trailingSlash: true, Next.js should create the static pages like that:

https://example.com/locations/berlin/index.html

But instead it creates pages like that:

https://example.com/locations/berlin.html

// next.config.js
module.exports = {
    target: "serverless",
    trailingSlash: true,
};

For our static pages, we use a pages/[...slug].js file that exports our static paths with fallback: false.

Since we use server rendered pages too, we can't use next export.

# netlify.toml

[build]
    command = "yarn build"

[[plugins]]
    package = "@netlify/plugin-nextjs"
// package.json

{
  ...
  "scripts": {
    "build": "next build",
    ...
  }
}

Versions

  • next: 10.2.0
  • @netlify/plugin-nextjs: 3.2.0

Expected behavior

  • Pages without trailing slash are redirected with status code 301 to the url with a trailing slash
  • Pages with trailing slash are loaded directly with status code 200

Solution

  • There doesn't seem to be an easy way to make trailing slashes work with Next.js on Neltify at the moment, so we decided to switch to Vercel. The platform seems to be better suited for Next.js overall, which is not surprising as it's developed by the same company.