Nuxt Redirects in 4 Steps

Nuxt uses automatic routing. Nuxt automatically transforms the “pages” folder into basic routes. Therefore, if you create index.vue in the “pages” folder, it will be your homepage. Any nested folders can be accessed through the url from the directory path. Imagine you have a “customers” folder inside of your “pages” folder. Inside of your “customers” folder, you have another “index.vue” file. If you navigate to http://localhost:3000/customers, you would see this page.

However, now, I want to redirect the user from the “/” to “/customers” (homepage to customers page). How could I do this? We will have to use some middleware. Sounds complex. Hopefully, we can accomplish this in 4 steps.

  1. Create a folder in your root directory called “middleware”
  2. Create a file called “redirects.js” in the “middleware” folder
  3. In redirects.js, paste the following code. Here, we are setting up a middleware function. The code below will reroute the user from the homepage to the “customers” page with a 301 code (used for redirects). Change the bolded code below to fit your needs.
export default function(req, res, next) {
const redirects = [
{
from: "/",
to: "/customers"
}
]
const redirect = redirects.find((r) => r.from === req.url)
if (redirect) {
res.writeHead(301, { Location: redirect.to })
res.end()
} else {
next()
}
}

4. Add the redirects.js middleware to the nuxt.config.js file so that our code will run.

serverMiddleware: [
'~/middleware/redirects.js'
],

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store