Marcin Lubowicz
Marcin Lubowicz

Reputation: 38

How to set global baseUrl for Axios in Gatsby?

I am building website using Gatsby and I am fetching some data from my backend. I want to set set global baseUrl for Axios. Normally I will do something like this:

import axios from "axios";

axios.defaults.baseURL = "API_ADDRESS";

But where should I put this in Gatsby to make it global?

Upvotes: 0

Views: 318

Answers (2)

Ahmed Atri
Ahmed Atri

Reputation: 11

in case someone else comes here, the suggestion of mohammed agboola is not accurate, using onInitialClientRender the base url will change to client side url when you refresh the page, in the same file gatsby-browser.js you should be using onClientEntry instead of onInitialClientRender :

export function onClientEntry() {
 axios.defaults.baseURL = "YOUR_BASE_URL" 
}

Upvotes: 1

Mohammed Agboola
Mohammed Agboola

Reputation: 37

Create a gatsby-browser.js file in the root folder of your project, if you don't have one. and use the lines of code below:

const axios = require("axios").default

exports.onInitialClientRender = () => {
  axios.defaults.baseURL = "YOUR_BASE_URL_HERE"
}

The above lines of code set axios baseURL when Gatsby App is rendered to the browser. Hope this answers your question.

Upvotes: 0

Related Questions