Static GitHub Issues

[2809] context.redirect() acts weirdly when the path doesn't start with a slash

prev: Optimization
next: v-for variable is undefined in string interpolated v-bind, but works in mustaches

I have a middleware that handles redirects in my app. For example when a user visits a path, I redirect them immediately to a different path which includes a language code.

I was using the following code: redirect(301, langCode + "/" + originalPath)

Notice that the path starts with the language code immediately.

The redirect works on server side as expected (when I open an url directly that results in a redirect right away) but it fails when the redirect happens at client side, for example when the user clicks on a nuxt-link. Instead of being redirected to http://localhost:3000/en/path I'm redirected to http://en/path, which is obviously wrong.

This can be fixed by making sure the path where I redirect starts with a slash.

The issues in my opinion:

  • If the slash at the beginning of the path is not obligatory, then there is a bug that causes the weird behavior described above.
  • It it is, then it's not documented, and the omission is not handled gracefully.

The issue can be simply reproduced by the following setup:

1) Create a project from nuxt-community/starter-template 2) Add a page called "test". Inside place a nuxt-link targeting "/" 3) Create a middleware, add it to nuxt.config.js inside the router.middleware array. The middleware's code:

    export default function ({route}
    {
        if (route.fullPath === "/") {
            redirect(301, "test")
        }
    }

4) Run in dev mode

Expected result: When you open http://localhost:3000/. It should work, you should be redirected to /test. When you click on the link on the test page it should load /, where the middleware would redirect you to /test again. That's not what happens, you'll get redirected to http://test/

<!--cmty--><!--cmty_prevent_hook--><div align="right"><sub><em>This question is available on <a href="https://nuxtjs.cmty.io">Nuxt.js</a> community (<a href="https://nuxtjs.cmty.io/nuxt/nuxt.js/issues/c2441">#c2441</a>)</em></sub></div>