graphqlapollohttp-status-code-301nuxt.jsvue-apollo

How to process 301 redirects with Nuxt ServerMiddleware and Apollo GraphQL


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?


Solution

  • finally, I found the solution in nuxtjs's github

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

    Done!