Use Refresh Tokens in Node.js (and axios): Receiving 401 error (access_denied, Unauthorized)

I was receiving a 401 error when using a refresh token to acquire a new access token in a Node.js app, despite following the example code in the docs: Use Refresh Tokens

Turns out, one needs to serialize the request’s data object. Eg:

const axios = require("axios")
const params = new URLSearchParams({
  grant_type: 'refresh_token',
  client_id: 'YOUR_CLIENT_ID',
  client_secret: 'YOUR_CLIENT_SECRET',
  refresh_token: 'YOUR_REFRESH_TOKEN',
});

const options = {
  method: 'POST',
  url: 'https://YOUR_DOMAIN/oauth/token',
  headers: {'content-type': 'application/x-www-form-urlencoded'},
  data: params.toString(),
};

try {
  const response = await axios(options);
  console.log(response.data);
} catch (error) {
  console.error(error);
}

Posting this in case it is of aid to others.

2 Likes

Interesting, and happy to know you got around the 401 - Thanks for sharing with the community!

2 Likes