Search code examples
node.jsaxiosjwtnuxt.jsnuxt-auth

Axios - Prevent sending JWT token on external api calls


I'm building a fullstack app with nuxt + express and I have finally managed to include an authentication between my frontend/backend with passport and jwt.

I want to make additional api requests to my own github repo for fetching the latest releases (so a user gets a information that an update exists). This requets failed with a "Bad credentials" messages. I think this happens because my jwt token is sent with it (I can see my token in the request header).

My question is, is it possible to prevent axios from sending my JWT token in only this call? First, to make my request work and second, I don't want the token to be sent in external requests.

Example:

const url = 'https://api.github.com/repos/xxx/releases/latest'
this.$axios.get(url)
    .then((res) => {
        this.latestRelease = res.data
    }).catch((error) => {
        console.error(error)
    })

Solution

  • transformRequest

    You can override the Authorization for a specific call by passing an options object to your get request and transforming your request headers:

    const url = 'https://api.github.com/repos/xxx/releases/latest';
    this.$axios.get(url, {
      transformRequest: (data, headers) => {
        delete headers.common['Authorization'];
        return data;
      }
    })
    .then((res) => {
      this.latestRelease = res.data;
    }).catch((error) => {
      console.error(error);
    })
    

    As explained in their GitHub readme:

    transformRequest allows changes to the request data before it is sent to the server. This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'. The last function in the array must return a string or an instance of Buffer, ArrayBuffer, FormData or Stream. You may modify the headers object.

    Creating a specific instance

    You can create an instance of axios for different scenarios. This allows you to separate your axios calls that require an authorization header and those who don't. Each instance has its own 'global' options:

    const axiosGitHub = axios.create({
      baseURL: 'https://api.github.com/',
      timeout: 1000,
      headers: {}
    });
    
    // won't include the authorization header!
    const data = await axiosGithub.get('repos/xxx/releases/latest');