Friday, 28 October 2022

Nuxt proxy works in dev mode but fails in generated/staging, why?

To avoid users know what endpoint we are requesting data, we are using @nuxtjs/proxy

This config in nuxt.config.js

const deployTarget = process.env.NUXTJS_DEPLOY_TARGET || 'server'
const deploySSR = (process.env.NUXTJS_SSR === 'true') || (process.env.NUXTJS_SSR === true)

And the proxy settings

proxy: {
  '/api/**/**': {
    changeOrigin: true,
    target: process.env.VUE_APP_API_URL,
    secure: true,
    ws: false,
    pathRewrite: { '^/api/': '' }
  }
},

Also we deploy like so

NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt build && NUXTJS_DEPLOY_TARGET=server NUXTJS_SSR=false nuxt start

Also in the httpClient that normally is

constructor (basePath, defaultTimeout, fetch, AbortController) {
  this.basePath = basePath
  this.defaultTimeout = parseInt(defaultTimeout, 10) || 1000
  this.isLocalhost = !this.basePath || this.basePath.includes('localhost')
  this.fetch = fetch
  this.AbortController = AbortController
}

Has been modified like so:

constructor (basePath, defaultTimeout, fetch, AbortController) {
  this.basePath = '/api'
  this.defaultTimeout = parseInt(defaultTimeout, 10) || 1000
  this.isLocalhost = !this.basePath || this.basePath.includes('localhost')
  this.fetch = fetch
  this.AbortController = AbortController
}

The fetch options are

_getOpts (method, options) {
  const opts = Object.assign({}, options)
  opts.method = opts.method || method
  opts.cache = opts.cache || 'no-cache'
  opts.redirect = opts.redirect || 'follow'
  opts.referrerPolicy = opts.referrerPolicy || 'no-referrer'
  opts.credentials = opts.credentials || 'same-origin'
  opts.headers = opts.headers || {}
  opts.headers['Content-Type'] = opts.headers['Content-Type'] || 'application/json'
  if (typeof (opts.timeout) === 'undefined') {
    opts.timeout = this.defaultTimeout
  }

  return opts
}

So that's making a request to https://api.anothersite.com/api/?request..

And in localhost using npm run dev its working just fine, it requests and fetchs the desired data.

But some how, when we deploy it to the staging environment all those request return

{ "code": 401, "data": "{'statusCode':401,'error':'Unauthorized','message':'Invalid token.'}", "json": { "statusCode": 401, "error": "Unauthorized", "message": "Invalid token." }, "_isJSON": true }

Note that

  • the front is being deployed to ourdomain.com that has basic auth and we are properly authenticated
  • The requests in both in local and staging are done to api.anothersite.com without basic auth where the data is served from a Strapi (it doesn't need any token)

is it posible that this response that we are getting is because of the basic auth from the frontend? even that we are logged in?



from Nuxt proxy works in dev mode but fails in generated/staging, why?

No comments:

Post a Comment