UNDERSTANDING AXIOS PROXY AND GETTING IT TO WORK WITH NUXT.JS

Understanding axios proxy and getting it to work with nuxt.js

The proxy settings can be quite confusing when trying make axios requests in Nuxt. I am writing this article to try and clarify how it works.

Test the proxy works with a public API

The axios config in nuxt.config.js

// Axios module configuration:
// https://go.nuxtjs.dev/config-axios
  axios: {
    // WARNING: proxy doesn't work with nuxt generate,
    // have to use a prefix and set an API_URL
    proxy: true,
  }

The proxy config

proxy: {
  '/api/': {
    target: 'https://jsonplaceholder.typicode.com/',
    pathRewrite: { '^/api/': '/posts/1' }
  },
}

Make a simple axios get request inside your app

this.$axios
  .get("/api/")
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error(err);
  });

The console log should be as follows:

Proxy created: /api/  -> https://jsonplaceholder.typicode.com/
Proxy rewrite rule created: "^/api/" ~> "/posts/1"

You can see the proxy rewrites the path /api/ into /posts/1 and appends it to our target url. So the final request would return the results for https://jsonplaceholder.typicode.com/posts/1

Axios Proxy will not work with Nuxt Generate in static mode

The proxy settings don't work with static mode, so we can skip using the proxy all together and just configure a prefix which would be the root endpoint of our API.

baseUrl, prefix & API_URL

baseUrl Defines the base URL which is used and prepended to make server side requests.

Environment variable API_URL can be used to override baseURL.

WARNING: baseURL and proxy cannot be used at the same time, so when the proxy option is in use, you need to define prefix instead of baseURL.

In nuxt.config.js

// Axios module configuration:
// https://go.nuxtjs.dev/config-axios
  axios: {
    // WARNING: proxy doesn't work with nuxt generate,
    // have to use a prefix and set an API_URL
    proxy: false,
    prefix: process.env.API_URL
  }

In your .env file

API_URL=https://jsonplaceholder.typicode.com/

Now all of our requests will start with that string and the endpoint will just be added to the end of the URL. We need to make sure we use the correct endpoints though, this time we would be calling /posts/1 not /api because there is no path rewrite from the proxy module.

The request without a proxy would look like this

this.$axios
  .get("/posts/1")
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.error(err);
  });

The only caveat really with this, is that we can only have one API_URL. So all of our requests need to be made to a single API.

If you want to work with multiple API's fetching data then you can handle these requests server side. For example using a node serverless function that's basically an express api that returns the data we need.

FREELANCE DEVELOPER FOR HIRE

LOOKING FOR A WEB DEVELOPER?