VueRouter - localStorage gets cleared when no trailing slash is added in URL

Viewed 78

I use localStorage to store a JWT-token.

When I go to https://www.example.com/my-web-app/, I can see the JWT token in the Developer Tools --> Application. When I go to https://www.example.com/my-web-app, no data in the localStorage is visible.

This means that user of the application has to log in over and over again if he doesn't add a trailing slash to the URL. Anyone have an idea where the cause might be?

Dependencies

{
   "vue": "^2.6.11",
   "vue-router": "^3.1.5"
}

VueRouter config:

{
    path: '/',
    name: 'home',
    component: Home,
    meta: {
        requiresAuth: true
    }
},
{
    path: '/:catchAll(.*)',
    name: 'NotFound',
    component: NotFound
}

htaccess config (located in /my-web-app)

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /my-web-app/
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /my-web-app/index.html [L]
</IfModule>
1 Answers

You can create a utility function that auto add the trailing slash on every route when is not :

util.js

export function trailingSlash (str) {
  return str.endsWith('/') ? str : str + '/'
}

in the router file, router/index.js

    import { trailingSlash } from 'util.js'
    ...
    ...
    router.beforeEach((to, from, next) => {
        return to.path.endsWith('/') ? next() : next(trailingSlash(to.path))
    })

A trailing slash is going to be added a the end of the url.

Related