next.js: trailing slash in link for legit page works for client side navigation but leads to not found bundle and 404 on hard refresh (ssr)

trailing slash in link for legit page works for client side navigation but leads to not found bundle and 404 on hard refresh (ssr)

Bug report

Describe the bug

let me know if title needs further clarification.

all relevant issues has been closed with reasoning that its been fixed in 6-canary (I believe it is not) or by improved serve (which is true only in perhaps production static export).

I’m rewriting my existing blog to next.js and i previously used trailing slashes. Latest serve can help with it once i build my next.js powered blog. But in order to fix dev env i need either to get rid of trailing slashes and utilize 301 Moved Permanently in prod; or live with broken trailing slash support in dev.

To Reproduce

Here is minimal reproducible case (link to repro repo is below snippet):

// pages/index.js
import Link from "next/link";

export default () => (
  <Link href="/about/">
    <a>About</a>
  </Link>
);

// pages/index.js
export default () => "about";

Minimal reproducible repo https://github.com/iamstarkov/next.js-trailing-slash-bug-demo

  1. clone repo git clone https://github.com/iamstarkov/next.js-trailing-slash-bug-demo
  2. change directory cd next.js-trailing-slash-bug-demo
  3. install deps yarn
  4. run dev: yarn dev
  5. open http://localhost:3000/
  6. open devtools’ network tab
  7. observe http://localhost:3000/_next/static/development/pages/about.js being 200ed
  8. observe http://localhost:3000/_next/on-demand-entries-ping?page=/about/ being 200ed
  9. observe http://localhost:3000/about/ being 404ed
  10. observe persistent attempts to resolve http://localhost:3000/about/
  11. observe in the terminal Client pings, but there's no entry for page: /about/
  12. refresh the page
  13. observe 404 page.
  14. remove trailing slash in the url or click http://localhost:3000/about
  15. observe page being 200ed
  16. to ensure error persistence repeat steps 5-15 once.

Expected behavior

  1. /about/ shouldnt be resolved as 404 not found
  2. /about/ should be resolved as 200 ok
  3. Server should not print Client pings, but there's no entry for page: /about/
  4. both /about and /about/ should work the same way

Screenshots

N/A

System information

  • OS: macOS High Sierra 10.13.6 (17G65)
  • Browser (should not matter, but can repro’ed in chrome 69.0.3497.100 and safari Version 12.0 (13606.2.11) (was the same for safari 11)
  • Version of Next.js: 7.0.0 (could repro on 5.x and 6.x)

Additional context

Add any other context about the problem here.

If you change this code in https://github.com/zeit/next.js/blob/459c1c13d054b37442126889077b7056269eeb35/server/on-demand-entry-handler.js#L242-L249

or node_modules/next/dist/server/on-demand-entry-handler.js locally

          const { query } = parse(req.url, true)
          const page = normalizePage(query.page)
+         console.log('query.page', query.page);
+         console.log('page', page);
+         console.log('Object.keys(entries)', Object.keys(entries));
          const entryInfo = entries[page]

          // If there's no entry.
          // Then it seems like an weird issue.
          if (!entryInfo) {
            const message = `Client pings, but there's no entry for page: ${page}`

and restart next dev and open http://localhost:3000/ and click about link then:

  • for /about
    query.page /about
    page /about
    Object.keys(entries) [ '/', '/about' ]
    
  • for /about/:
    query.page /about/
    page /about/
    Object.keys(entries) [ '/', '/about' ]
    Client pings, but there's no entry for page: /about/
    

I think the problem (at least part of it) is in inability of onDemandEntryHandler’s middleware to find page in entries if page has trailing slash.

I hope my 2 hours of investigation and preparation can help with fixing this issue.

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 189
  • Comments: 124 (35 by maintainers)

Commits related to this issue

Most upvoted comments

We’re about to land a feature fixing this—a day or so!

@cnblackxp thanks for the suggestion. That helped me. Here is how I implemented it in order to keep the default behavior for non-trailing 404s (i.e. I am simply re-exporting the default Error implementation):

import Error from "next/error";
import Router from "next/router";

export default Error;

Error.getInitialProps = ({ res, err, asPath }) => {
  const statusCode = res ? res.statusCode : err ? err.statusCode : 404;

  if (statusCode && statusCode === 404) {
    if (asPath.match(/\/$/)) {
      const withoutTrailingSlash = asPath.substr(0, asPath.length - 1);
      if (res) {
        res.writeHead(302, {
          Location: withoutTrailingSlash
        });
        res.end();
      } else {
        Router.push(withoutTrailingSlash);
      }
    }
  }

  return { statusCode };
};

FWIW this is being worked on already #13333

This is certainly a massive issue especially because / routes throw Error pages and that hurts SEO

It doesn’t hurt your SEO. google treats trailing slash as a different page. Having it 404 doesn’t impact SEO any more than any other non existing page in your site. Besides, as long as you never link to it with a trailing slash, google won’t try to crawl it in the first place. This issue, while still being a valid issue, is way less critical than you all make it to be.

How long does it take for feature to get from canary to master?

I apologize because I’m a Next JS newbie, although I have software development experience on other SDKs and platforms.

I think this “bug” surprised me the most. For me, it violated the “principle of least astonishment.” I simply expected my /about/ and /about to work the same, since I placed an index.tsx into my /pages/about/ folder.

I first started making web sites in the late 1990s with HTML FTP’d to my server, and later moved on to PHP & Apache, and eventually Java servers. Now I specialize in mobile apps. It just feels weird to me that this behavior is not the default, and that I’d have to write a custom server page to fix it on my dev server.

I plan to do a static export, so it won’t show up in production even if I don’t write the custom server. It does make dev and debugging slightly more annoying though.

Can we get a “next dev” flag that fixes this so we lazy developers don’t need to write extra routing logic just for dev/debug time?

Thanks!

p.s.: Yes, I do know that /about and /about/ are completely different URLs. I just got really confused when I put an index.tsx file inside my /pages/about/ folder, and discovered that it only works with the /about path but does not work with /about/. I would be less surprised if it was the other way around.

p.p.s.: It was extra confusing when I have a <Link></Link> component that points to /about/ and it works as expected. Then when I hit refresh on my browser, it immediately 404s, even though the URL didn’t change. That was very surprising. 😄

This is certainly a massive issue especially because / routes throw Error pages and that hurts SEO (which is one of the primary draws of Next).

The 301 redirects and the custom express servers all seem to be hacks rather than fixes. In my case, I have a full working application built on Next with no custom Express server - everything else works perfectly, but now I’m having to create a new Express server only because of the trailing slash issue. The effort required seems to be disproportionate considering this is a hack. I would love if this could be bumped up in priority! Due to this reason, I’m hearing grumblings in my team about having used Next as opposed to something like vanilla React/Angular and it certainly weakens the case for Next.

PS: I absolutely love working with Next ❤️

I’m shocked that this issue not solved in any way for about year! Do Next.js team need any other reasons to start fixing this?

URL’s should work regardless of trailing slash. Check any site on the web.

If this is out of scope of Next.js, give us ability to configure this in Now. I’m really confused that Zeit team ignores such critical issues for years.

This has now been resolved in next@^9.4.5-canary.17!

I’m using version 9 and this issue is still not resolved

More importantly, the redirect solution doesn’t work for those who are maintaining sites that area already set up to add a slash rather than remove one in production. I don’t think the framework should be dictating this choice arbitrarily.

Thanks everyone for some of your workarounds above. They worked!

However, do we have any official way to fix this issue from Next’s team? This issue has been here for years.

when I faced this issue I came up with this solution

in my _error.js page

Error.getInitialProps = ({ res, err, asPath }) => {
    const statusCode = res ? res.statusCode : err ? err.statusCode : 404;

    const checkForTrailingSlashes = () => {
        if (asPath.match(/\/$/)) { // check if the path ends with trailing slash
            const withoutTrailingSlash = asPath.substr(0, asPath.length - 1);
            if (res) {
                res.writeHead(302, {
                    Location: withoutTrailingSlash
                })
                res.end()
            } else {
                Router.push(withoutTrailingSlash)
            }
        }
    }

    if (statusCode && statusCode === 404) {
        checkForTrailingSlashes();
    } else {
        // 
    }
    return { statusCode };
}

is it a good way to overcome the issue ?

I’m using nextjs 7 and trailing slash is producing a 404 for me on both dev and prod:

  • on initial page load
  • on page refresh

And affects:

  • an external link
  • an internal link
  • URL pasted into the browser

Simply removing the trailing slash fixes the issue.

Trailing slashes are often added by browsers, servers and/or other services where links might be pasted so while I can control internal links, it’s hard to control what at what links external users might be arriving on

Took @cansin 's solution and added the ability to handle query parameters

MyError.getInitialProps = async ({ res, err, asPath }) => {
  // Capture 404 of pages with traling slash and redirect them
  const statusCode = res 
    ? res.statusCode
    : (err ? err.statusCode : 404);

  if (statusCode && statusCode === 404) {
    const [path, query = ''] = asPath.split('?');                                                                                                                                                                                             
    if (path.match(/\/$/)) {
      const withoutTrailingSlash = path.substr(0, path.length - 1); 
      if (res) {
        res.writeHead(302, {
          Location: `${withoutTrailingSlash}${query ? `?${query}` : ''}`,
        }); 
        res.end();
      } else {
        Router.push(`${withoutTrailingSlash}${query ? `?${query}` : ''}`);
      }   
    }   
  }

Here’s how I fixed it, https://medium.com/@thisisayush/handling-404-trailing-slash-error-in-nextjs-f8844545afe3

Thank you, though this requires a custom server when developing locally, and one shouldn’t be required.

@timneutkens Any chance a fix for this issue can be worked into the development schedule?

I decided to implement a custom server to handle this and it turns out it’s easy to do, and you can still use next.js’s file-based routing system. That way you can rewrite the URL that next.js sees and the real URL still has a slash at the end:

const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')
const conf = require('./next.config.js')

const PORT = process.env.PORT || 5000

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

app.prepare().then(() => {
    createServer((req, res) => {
        // If there is a slash at the end of the URL, remove it before sending it to the handle() function.
        // This is a workaround for https://github.com/zeit/next.js/issues/5214
        const url =
            req.url !== '/' && req.url.endsWith('/')
                ? req.url.slice(0, -1)
                : req.url
        // Be sure to pass `true` as the second argument to `url.parse`.
        // This tells it to parse the query portion of the URL.
        const parsedUrl = parse(url, true)

        handle(req, res, parsedUrl)
    }).listen(PORT, err => {
        if (err) throw err
        console.log(`> Ready on http://localhost:${PORT}`)
    })
})

See https://nextjs.org/docs/advanced-features/custom-server

I’m new to Next but what is the workaround you folks are using for this issue?

GitHub urls are irrelevant

@timneutkens @Janpot

I tried the latest next canary (9.4.5-canary.27) but when I create test page and I access www.example/test/ it redirects to www.example/test I think behavior for both cases should be the same.

When access www.example/test/ it should stay on www.example/test/. When access www.example/test it should stay on www.example/test. I test it on Nuxt.js, it works the same behavior that I describe above.

This has now been resolved in next@^9.4.5-canary.17!

And how exactly it is resolved? just removing the trailing slash? if i access “www.site.com/help/” i get redirected to: “www.site.com/help” , can we have an option there we opt for leaving ending slash? accessing “www.site.com/help/” or “www.site.com/help” will leave or redirect or add “/” at the end to have: “www.site.com/help/”

I guess the trailingSlash option won’t work for next export? What’s the best way to redirect /page/ to /page (or vice versa) in, say, github pages?

I’m in the same boat today. I’m using next export with GitHub pages for hosting.

  • Visiting www.website.com/about is fine
  • Visiting www.website.com/about/ results in a 404.

I still can’t find a solution for this one.

FYI: There’s an RFC that might interest you https://github.com/zeit/next.js/issues/9081

// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: "/:path*/",
        destination: "/:path",
        statusCode: 301
      }
    ];
  }
};

@Janpot

It doesn’t hurt your SEO. google treats trailing slash as a different page. Having it 404 doesn’t impact SEO any more than any other non existing page in your site.

I take your point that it doesn’t particularly hurt SEO innately. But it does put additional pressure on developers to get the URL definitions right every time, which is subject to human errors. A developer that is new to Next wouldn’t necessarily know that the following (perfectly normal looking) URL will lead to a 404 page. <Link href='/people/'>

A mature framework shouldn’t be subject to such human errors ideally imo.

Besides, as long as you never link to it with a trailing slash, google won’t try to crawl it in the first place.

Again - there exists the issue of people accidentally linking to the www.mysite.com/people/ instead of www.mysite.com/people (both of which seem to be exactly the same for users - even most developers).

Both of these scenarios can affect SEO.

Now, not considering the SEO impact, there’s also the semantic meaning of the URL - what does www.mysite.com/people**/** point to? Ideally because it is pointing to a directory, Next should return whatever is in pages > people > index.js (as opposed to pages > people.js for www.mysite.com/people) but instead it returns nothing, which is a very high level flaw in how the routing works.

Major routing libraries already have some provision for this - like isExact in the case of React Router

While I understand where you’re coming from, I still think this is a glaring issue that needs to be bumped up

Any update for nextjs 9 ?

Projects that use next export will have all of their <Link />s on the client-side correctly updated, but the server-side redirect will require manual configuration. Projects deployed with the serverless target or next start will configure these settings automatically.

Hi @Timer Can you explain more? How can I config manually? So here is my situation. On my website, I use next-i18next. After I deployed with next build && next export, all of the internal links work but when manually enter URL, NONE of them works and lead to 404 error. From here I decided to use trailingSlash:true and so manually enter /pricing will work now but /zh/pricing leads to 404 errors.

@Timer once this reaches a full release, would we still need to use the experimental option?

No, would just be available as-is.

I think behavior for both cases should be the same.

The reason for a redirect is to make sure search engines don’t see duplicate content. What’s your exact use-case?

@Valnexus see #13333, it includes an experimental option:

module.exports = {
  experimental: {
    trailingSlash: true
  }
}

How long does it take for feature to get from canary to master?

When it’s ready. There are still edge cases in the handling that are being solved. Once those have been fixed it can go to stable.

@AlexSapoznikov 's solution worked well for us with Netlify (which adds a trailing slash by default). Here is an advanced version that adds support for query params:

import App from "next/app";

export default class MyApp extends App {
  render() {
    const { Component, pageProps, router, router: { asPath } } = this.props;

    // Next.js currently does not allow trailing slash in a route, but Netlify appends trailing slashes. This is a
    // client side redirect in case trailing slash occurs. See https://github.com/zeit/next.js/issues/5214 for details
    if (asPath && asPath.length > 1) {
      const [path, query = ""] = asPath.split("?");
      if (path.endsWith("/")) {
        const asPathWithoutTrailingSlash = path.replace(/\/*$/gim, "") + (query ? `?${query}` : "");
        if (typeof window !== "undefined") {
          router.replace(asPathWithoutTrailingSlash, undefined, { shallow: true });
          return null;
        }
      }
    }

    return <Component {...pageProps} />;
  }
}

For SEO, rel="canonical" may help, but still need to fix this 404 issue.

The problem with implementing a workaround in Error component is that it will throw notifying error in development which bothers me. Some improvement to my previous client side redirect:

What improved is that now it uses next/router in client side and the url replacement happens without a reload.

pages/_app.jsx

import App from 'next/app';
import Router from 'next/router';

export default class MyApp extends App {
  render() {
    const { Component, pageProps, router: { asPath, route } } = this.props;

    // Next.js currently does not allow trailing slash in a route.
    // This is a client side redirect in case trailing slash occurs.
    if (pageProps.statusCode === 404 && asPath.length > 1 && asPath.endsWith('/')) {
      const routeWithoutEndingSlash = route.replace(/\/*$/gim, '');
      const asPathWithoutEndingSlash = asPath.replace(/\/*$/gim, '');

      if (typeof window !== 'undefined') {
        Router.replace(routeWithoutEndingSlash, asPathWithoutEndingSlash);
      }
      return null;
    }

    return <Component {...pageProps} />;
  }
}

also thanks to @mbrowne for 404 fix 😃

How about this?

pages/_app.jsx

import App from 'next/app';

export default class MyApp extends App {
  render() {
    const { Component, pageProps, router: { asPath } } = this.props;

    // Next.js currently does not allow trailing slash in a route.
    // This is a client side redirect in case trailing slash occurs.
    if (asPath.length > 1 && asPath.endsWith('/')) {
      const urlWithoutEndingSlash = asPath.replace(/\/*$/gim, '');

      if (typeof window !== 'undefined') {
        window.location.replace(urlWithoutEndingSlash);
      }
      return null;
    }

    return <Component {...pageProps} />;
  }
}

I see others have posted their solutions, so I wanted to share my approach : https://github.com/DevSpeak/next-trailingslash

Some improvements and support for dynamic routed pages when it comes to ?= should be done IMO, but this is only for showing the idea.

There exists the issue of people accidentally linking to any non-existing url, why would/some/path/ be less non-existing than /some/path/dhgfiuwo?

For case /some/path/dhgfiuwo - people expect tha dhgfiuwo route can to be missing. (For example, user dhgfiuwo cannot be found in system and way users/dhgfiuwo is wrong. The absence of a user in the system is an expected occurrence.) For case /some/path/ - people expect this path to be same as /some/path, because this is default behavior on other sites. Therefore, a failure in would/some/path/is less non-existing than /some/path/dhgfiuwo.

@NathanielHill I could reproduce it on next@7

@ziserman If we have several way to solve it, we should keep the same url without redirect for user experience.

@Janpot https://github.com/nuxt-community/nuxt-i18n/issues/422

Nuxtjs have several options to choose (undefined, true, false)

Should Nextjs have serveral options to choose too?

If it has a problem with search engines, Why Github and Twitter did not fix it?

@armspkt It is not a problem since there are several ways to solve it. For example Twitter uses <link rel="canonical"> attribute to tell search bots which page they should crawl and other versions should be marked as duplicated.

So redirect is a viable way to make SEO on your website. You can read more info here.

This is a very old issue, is there a reason it is not addressed for so long?

2020 and this bug still hapens. Unbelievable

@mbrowne We actually have a bunch of reasons to use a custom server, but the main thing that has prevented me from implementing one so far is the fact that you lose Automatic Static Optimization. Do you know if it’s possible to manually specify static routes?

Directory pages are not served with trailing slash in next export

I think we can’t agree on this and it should be configurable.

I actually want the trailing slash always, the relative urls are easier to reason about when all pages end with trailing slash.

For instance it makes no sense that /about/index.tsx is /about instead of /about/, but understandable now that next expects without trailing slash. If all pages were to end in slash it would allow pages to contain subpages in the future, which I think is more extensible way for pages.

Making relative links inside /about/index.tsx file is now cumbersome. If you make a link ./mysubpage/ it points to root of the site instead. This makes the subpages non-renameable. I can’t make a directory /about/ full of pages that I can just rename, because I should go and edit the relative links too.

Also the wget -r site produces sensible results with having always trailing slashes, producing index.html files.

However changing this setting is massively breaking change since all sites expect non-trailing slashes, so it must be configurable.

Oauth federation providers often require trailing forward slashes so this behavior makes a simple flow very complicated. What is the technical challenge in implementing this behavior? Or is this a design decision from next?

I haven’t seen it mentioned thus far in this thread, but I am not experiencing this issue after deployment with Now, I’m only experiencing it locally when testing with now dev.

For a quick solution, you can replace the default _error page (as in @DevSpeak’s example).

@DevSpeak, I’d recommend a few changes for your repo:

  • Avoid 301 redirects – they’re permanently cached by browsers, and can cause you a lot of pain. In most cases, all you need is a 302.
  • Your errorCode ternary can be updated (it was outdated in the docs until last week)
  • This is server-side only, so you can wrap it with if (typeof window === 'undefined') { ... } to tree-shake it from the client bundle

Here’s what I’m using in a Typescript project (based on the built-in error page):

/pages/_error.tsx (or remove the TypeScript types and name it /pages/_error.jsx):

import React from 'react';
import Head from 'next/head';
import { NextPageContext } from 'next';

const statusCodes: { [code: number]: string } = {
  400: 'Bad Request',
  404: 'This page could not be found',
  405: 'Method Not Allowed',
  500: 'Internal Server Error'
};

export type ErrorProps = {
  statusCode: number;
  title?: string;
};

/**
 * `Error` component used for handling errors.
 */
export default class Error<P = {}> extends React.Component<P & ErrorProps> {
  static displayName = 'ErrorPage';

  static getInitialProps({
    req,
    res,
    err
  }: NextPageContext): Promise<ErrorProps> | ErrorProps {
    const statusCode =
      res && res.statusCode ? res.statusCode : err ? err.statusCode! : 404;
    if (typeof window === 'undefined') {
      /**
       * Workaround for: https://github.com/zeit/next.js/issues/8913#issuecomment-537632531
       * Test vectors:
       * `/test/test/` -> `/test/test`
       * `/test/////test////` -> `/test/test`
       * `/test//test//?a=1&b=2` -> `/test?a=1&b=2`
       * `/test///#test` -> `/test#test`
       */
      const correctPath = (invalidPath: string) =>
        invalidPath
          .replace(/\/+$/, '')
          .replace(/\/+#/, '#')
          .replace(/\/+\?/, '?')
          .replace(/\/+/g, '/');
      if (req && res && req.url && correctPath(req.url) !== req.url) {
        res.writeHead(302, {
          Location: correctPath(req.url)
        });
        res.end();
      }
      const reqInfo = req
        ? `; Url: ${req.url}; IP: ${req.headers['x-forwarded-for'] ||
            (req.connection && req.connection.remoteAddress)};`
        : '';
      console.log(`Error rendered: ${statusCode}${reqInfo}`);
    }
    return { statusCode };
  }

  render() {
    const { statusCode } = this.props;
    const title =
      this.props.title ||
      statusCodes[statusCode] ||
      'An unexpected error has occurred';

    return (
      <div style={styles.error}>
        <Head>
          <title>
            {statusCode}: {title}
          </title>
        </Head>
        <div>
          <style dangerouslySetInnerHTML={{ __html: 'body { margin: 0 }' }} />
          {statusCode ? <h1 style={styles.h1}>{statusCode}</h1> : null}
          <div style={styles.desc}>
            <h2 style={styles.h2}>{title}.</h2>
          </div>
        </div>
      </div>
    );
  }
}

const styles: { [k: string]: React.CSSProperties } = {
  error: {
    color: '#000',
    background: '#fff',
    fontFamily:
      '-apple-system, BlinkMacSystemFont, Roboto, "Segoe UI", "Fira Sans", Avenir, "Helvetica Neue", "Lucida Grande", sans-serif',
    height: '100vh',
    textAlign: 'center',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center'
  },

  desc: {
    display: 'inline-block',
    textAlign: 'left',
    lineHeight: '49px',
    height: '49px',
    verticalAlign: 'middle'
  },

  h1: {
    display: 'inline-block',
    borderRight: '1px solid rgba(0, 0, 0,.3)',
    margin: 0,
    marginRight: '20px',
    padding: '10px 23px 10px 0',
    fontSize: '24px',
    fontWeight: 500,
    verticalAlign: 'top'
  },

  h2: {
    fontSize: '14px',
    fontWeight: 'normal',
    lineHeight: 'inherit',
    margin: 0,
    padding: 0
  }
};

Note, this also logs an error when the page is hit, so you can check your logs to fix any links/other issues.

also neither #6664 nor #6752 help with these, because experimental.exportTrailingSlash doesnt help because it is for next export only, I believe

@SamSverko @ACPK next export is really tough to work with for any URL manipulation. Things like subfolders and trailing slash redirects simply don’t work. We have a Cloudfront/S3 static site setup and the only way we could fix these issues was to run Lambda@Edge functions on each request and to fix things before they hit the next app. It’s a real pain. You could also do it by putting Caddy or Nginx in front of your static site.

It’s frustrating as other static site generators such as Hugo do this out of the box.

@mlbonniec I’ve minimized your comment because it causes severe performance regressions in a Next.js app.

The latest next@canary version fixes this bug, please upgrade instead!

The reason for a redirect is to make sure search engines don’t see duplicate content. What’s your exact use-case?

@Janpot Our API has trailing slashes in a lot of places. The Latest release raises a lot of 404’s on the backend since the Urls with trailing slashes (/api/test/ -> /api/test) do not match

@Janpot I saw https://github.com/issues/ and https://github.com/issues can access the same behavior without a redirect.

https://twitter.com/explore/ and https://twitter.com/explore, this one too.

If it has a problem with search engines, Why Github and Twitter did not fix it? I think it is the default behavior for any website.

There is no specific use-case, it just my opinion that it should work that way.

You can keep track of the PR here: #13333

To make this work with SSR I had to add the following to the @pjaws & @AlexSapoznikov solution:

  static async getInitialProps({ Component, ctx, router }) {
    /* Fixes the trailing-slash-404 bug for server-side rendering. */
    const { asPath } = router;
    if (asPath && asPath.length > 1) {
      const [path, query = ""] = asPath.split("?");
      if (path.endsWith("/") && path.length > 1) {
        const asPathWithoutTrailingSlash =
          path.replace(/\/*$/gim, "") + (query ? `?${query}` : "");
        if (ctx.res) {
          ctx.res.writeHead(301, {
            Location: asPathWithoutTrailingSlash,
          });
          ctx.res.end();
        }
      }
    }
    return {
      pageProps: Component.getInitialProps
        ? await Component.getInitialProps(ctx)
        : {},
    };
  }

Probably it’s a good idea to somehow generalize this functionality into a function that works both during SSR and during CSR and call it in both places (getInitialProps and render).

This has worked for pages with getServerSideProps and now urls with trailing slashes are returning same page without 404. But there is one glitch, I have few pages that use dynamic routes and getStaticPaths, I can’t use getServerSideProps onto them and thus when these dynamic routes are browsed with a trailing slash, they first return a 404 and then they redirect to the page.

I think @ronyeh had made a really good point here, so I really want an official solution for this issue 😦

I was able to make it work by using something like the following on my next.config.js:

exportPathMap: async function() {
  const paths = {
    '/': { page: '/' },
    '/authors/index.html': { page: '/authors' },
  };

  return paths;
},

Accessing /authors gives 302 pointing location to /authors/. I’m testing with http-serve, not sure if this behavior is server-specifiy.

@DevSpeak @bitjson Thanks for your suggestions. That’s certainly one way to go about this and certainly solves the issue very well. But considering that the _error.jsx is originally meant to handle errors and not house routing logic, in my opinion having all of this code there is hacky and quite declarative. Expecting every user to do this in every code base shouldn’t be a requirement - this should come out of the box. = I am of the opinion that this condition needs to be built in with the routing logic, with an option to opt out like React Router.

@NathanielHill

This is also completely unavoidable in the case of next export

Wait - I understood from reading the documentation that there is specific code to handle the trailing slash condition:

The pages will be exported as html files, i.e. /about will become /about.html.

It is possible to configure Next.js to export pages as index.html files and require trailing slashes, i.e. /about becomes /about/index.html and is routable via /about/. This was the default behavior prior to Next.js 9. You can use the following next.config.js to switch back to this behavior:

// next.config.js
module.exports = {
  exportTrailingSlash: true,
}

Even if this isn’t really an option for static HTML export via next export, I don’t agree with the logic that just because Next supports this (amazing) feature, other modes need to suffer (I don’t know the usage stats but I would assume more people use the regular with-server mode as opposed to serverless) especially when this has been known to be such a common use case

Yeah, that sounds like a problem @exentrich

I wouldn’t have guessed that behavior as I’ve been told there’s an implicit ^ and $ wrapped around the regex (meaning your example wouldn’t match). Maybe there’s a way to access the query string on it’s own to add it back 🤷‍♂️ Good luck

@NathanielHill thanks! I tried this solution, but query parameters are stripped out. For example /some/?query=1 will redirect to /some without query. Do you know how to fix it?

A similar issue… redirect when multiple forward slashes are added. Example: https://github.com/zeit/next.js////////////issues/5214