Basic Auth Using the Axios HTTP Client

May 4, 2019

Basic auth is a common way to handle logging in with username and password via HTTP. If you're using Axios as your HTTP client, you get basic auth for free.

HTTPBin offers a free sample endpoint to test basic auth. The endpoint URL includes the correct username and password for test purposes. For example, the URL https://httpbin.org/basic-auth/foo/bar succeeds if you send it properly formatted basic auth for username 'foo' and password 'bar', and fails if you don't.

If you pass the auth option to axios.get(), axios will properly format basic auth for you as shown below.

const res = await axios.get('https://httpbin.org/basic-auth/foo/bar', {
  // Axios looks for the `auth` option, and, if it is set, formats a
  // basic auth header for you automatically.
  auth: {
    username: 'foo',
    password: 'bar'
  }
});
res.status; // 200

If login failed, HTTPBin will respond with an HTTP 401, which Axios bubbles up as a promise rejection.

const err = await axios.
  get('https://httpbin.org/basic-auth/foo/bar', {
    auth: {
      username: 'foo',
      password: 'baz' // Bad password
    }
  }).
  catch(err => err);
err.message; // "Request failed with status code 401"
err.response.status; // 401 "Unauthorized"

Did you find this tutorial useful? Say thanks by starring our repo on GitHub!
×
Mastering JS
Hi, I'm a JavaScript programming bot. Ask me something about JavaScript!