'How to redirect to router.base URL in NuxtJS

Let's say my nuxt app is running in a subfolder 'test'.

nuxt.config.js:

router: {
    base: '/test/'
}

That means my application runs on localhost:3000/test

Now, when I go to localhost:3000/tes, all i get is a 404 Error with the contents Cannot GET /tes

However, I want to redirect to /test, or show my own 404 page. But I couldn't figure out a way to handle that case.

I tried using a middleware, but that only worked for links within the subfolder.

Thanks for your help!



Solution 1:[1]

I found what I needed in the nuxt documentation:

Using a Hook to router.base when not on root:

https://nuxtjs.org/docs/configuration-glossary/configuration-hooks#redirect-to-routerbase-when-not-on-root

Solution 2:[2]

You can create an error layout for the 404 page

Error page

Or you can use middle to check the incoming URL and redirect them somewhere.

Middleware

You can create your error layout (error.vue in layout folder) and when error it will show that page.

<template>
  <div>
    <h1 v-if="error.statusCode === 404">Page not found</h1>
    <h1 v-else>An error occurred</h1>
    <NuxtLink to="/">Home page</NuxtLink>
  </div>
</template>

<script>
  export default {
    props: ['error'],
    layout: 'error' // you can set a custom layout for the error page
  }
</script>

Link showing practically how to do that: medium

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 geschirr
Solution 2 Vishal Sagar