2

I am currently building a Vue / Nuxt app coupled with a modified Saleor installation to sell products online.

As we are migrating from an existing system we need to be able to process 301 redirects from our old website's URLs into the new websites URLs.

I have modified the API to respond to the following GraphQL query.

export const CHECK_REDIRECTS_QUERY = gql`
  query Redirect($oldPath: String) {
    redirect(oldPath: $oldPath) {
      oldPath
      newPath
    }
  }
`

Following on from this recommendation I have created the following code in a ~/serverMiddleware/redirect.js file

import { CHECK_REDIRECTS_QUERY } from '~/graphql/navigation/queries'

export default function(req, res, next) {
  console.log('redirects middleware')
  // context.userAgent = process.server ? context.req.headers['user-agent'] : navigator.userAgent
  this.$apollo
    .query({
      query: CHECK_REDIRECTS_QUERY,
      variables: {
        oldPath: '/test/11/old/'
      }
    })
    .then(({ data }) => {
      if (data.redirect.newUrl !== '') {
        res.writeHead(301, { Location: data.redirect.newUrl })
        res.end()
      }
    })
}

I have also added this to my nuxt.config.js file as follows:

 ... 
 serverMiddleware: ['~/serverMiddleware/redirect.js'],
 ...

This does not work but not only do I not get the redirect I would expect the console.log at the beginning of the function also does not fire.

Additionally, I have also tried using the code as it was written in the github recommendation and this is very "flakey" firing probably twice in about 50 server restarts.

I'm not picking up any console notifications that apollo cannot be used within the servermiddleware and the rest of the site seems to function correctly.

Also, - for clarification - I assume the middleware should just fire automatically on every page and does not need to be called manually from a component?

Pete Dermott
  • 663
  • 1
  • 9
  • 20
  • How are you accessing nuxt context (this) in server middleware to query apollo? I am getting undefined and according to the nuxt docs Nuxt Context is not available in server middleware? – ToddPadwick Jan 18 '22 at 17:59

3 Answers3

6

finally, I found the solution in nuxtjs's github

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

Done!

Ali
  • 1,528
  • 1
  • 10
  • 12
  • Excellent find! – ckhatton Nov 09 '20 at 04:47
  • Nice fine :) Looking at applying this myself. Until now, our error pages were querying our redirects API if the page hit a 404. However, it turns out some crawlers were failing to pick this up. But what I am concerned about with your solution is the fact that it is triggered on every page whether a 404 is hit or not, which means it's always going to cause performance issues. Have you found this causes any issues? – ToddPadwick Jan 18 '22 at 17:28
  • Thank you! res.end() is what I needed. I was trying to return the `res.writeHead()` which was causing endless loading. – CodeConnoisseur Sep 11 '22 at 15:24
  • @ToddPadwick did you find it causing issues with performance? – CodeConnoisseur Sep 11 '22 at 15:35
  • 1
    @CodeConnoisseur I ended up applying this solution which I outlined in this comment https://github.com/nuxt-community/redirect-module/issues/111#issuecomment-1061854078 – I was worried performance would not be as good as the 404 first approach but it seems to be okay – ToddPadwick Oct 12 '22 at 15:18
0

You can use it like this:

redirect(302, '/login')
redirect({ name: 'slug', params: { slug: mySlug } })
redirect('https://vuejs.org')

Follow this docs: https://nuxtjs.org/docs/internals-glossary/context/#redirect

huypham
  • 184
  • 3
  • 8
-1

The simplest way to organize redirects is to use Redirect Module

  • From Review: Hi, while links are a great way of sharing knowledge, they won't really answer the question if they get broken in the future. Add to your answer the essential content of the link which answers the question. In case the content is too complex or too big to fit here, describe the general idea of the proposed solution. Remember to always keep a link reference to the original solution's website. See: [How do I write a good answer?](https://stackoverflow.com/help/how-to-answer) – sɐunıɔןɐqɐp Jan 08 '21 at 14:25
  • Petes question requires apollo which the Redirect Module doesn't support from what I understand. – ToddPadwick Jan 18 '22 at 18:05