Kyrony
Kyrony

Reputation: 609

How to catch a route and redirect to Another Page in Nuxt 3

I have a website that I have rebuilt using Nuxt 3. Backlinks exists on numerous platforms and I need the old links to point to the new pages. Example: old(website.com/contact.html) new(website.com/contact)

I tried using middleware, but after deploying it, I get this error: 502 Error decoding lambda response

In my middleware/redirect folder I have this:

const redirects = [{
    'from' : '/contact.html',
    'to' : '/contact'
}]

export default function (req, res, next) {
    const redirect = redirects.find((r)=> r.from === req.url)

    if (redirect) {
        res.writeHead(301, { Location: redirect.to })
        res.end()
    } else {
        next()
    }
}

It works locally but not after deploying to netlify!

and I added this to my nuxtconfig file:

    serverMiddleware: [
        '~/middleware/redirect'
    ]

I thought that this middleware would act as a net to catch any req to the old contacts.html page and redirect them to the new contact page. but instead it sends that lambda error which I looked around and have not found a solid fix for. I am open to any solution including a different way of redirecting! Thank you!

Upvotes: 18

Views: 23375

Answers (2)

Felix Eklöf
Felix Eklöf

Reputation: 3740

Instead of building your own middleware, you can add your own router options. Here are the docs.

  1. Create a folder called app in the root of your project (same folder as nuxt.config.ts.
  2. Inside/app create file router.options.ts.
  3. Inside router.options.ts write:
import type { RouterOptions } from '@nuxt/schema';

// https://router.vuejs.org/api/interfaces/routeroptions.html
export default <RouterOptions>{
  routes: (_routes) => [
    {
      name: 'contact',
      path: '/contact',
      component: () => import('~/pages/contact.vue'),
      alias: '/contact.html',
    },
  ],
};

EDIT: You could also use definePageMeta with alias. Docs.

Upvotes: 2

moghwan
moghwan

Reputation: 2287

You can achieve redirections without middlewares by using the redirect option inside routeRules in nuxt.config.ts as below:

export default defineNuxtConfig({
    routeRules: {
        '/contact.html': { redirect: '/contact' },
        '/external-route': { redirect: 'https://example.com' },
    },
})

you can also define a new route that can be redirected to any internal or external page.

More rules options can be found here: https://nitro.unjs.io/config/#routerules, which mentioned in the official doc

Upvotes: 21

Related Questions