nuxt.jsvuejs3middleware

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!


Solution

  • 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