How to send Basic Auth with Axios in React & Node ?
Last Updated :
15 Mar, 2024
Basic Auth is a simple authentication scheme. It involves sending a username and password with each request to the server through HTTP. Axios is a popular HTTP client for making requests in JavaScript.
In this article, we will create a React App to demonstrate sending basic Auth with Axios and discuss the following approaches:
In this approach, we use the Axios library to request an HTTP POST to a login endpoint in the components.
Syntax:
const response = await axios.post('http://localhost:5000/login', { username, password });
// This statement should be wrapped inside an async function
Approach 2: Creating an Instance of Axios:
In this approach, we don't use the axios directly in the component, rather we make an instance of Axios with basic backend details such as base API string and basic headers. This helps avoid rewriting the base URL and headers repeatedly. Then we export the instance to make it usable in other components.
Syntax:
const instance = axios.create({
baseURL: 'http://localhost:5000',
headers: {
'Content-Type': 'application/json',
},
});
export default instance;
// import axios from the exported instance
const response = await axios.post('/login', { username, password });
Steps to Create Basic Express Server to Receive Basic Auth:
We will send the basic auth from frontend using axios. But it will require a server setup to receieve the test request. We will build that server first.
Step 1: Create a folder, enter into it and initialize a node app. Run the following commands to do that
mkdir server
cd server
npm init
Step 2: Install the dependencies to create a server
npm install cors express
Folder Structure(Backend):
express backend project structureThe updated dependencies in package.json file will look like:
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.2",
"nodemon": "^3.1.0"
}
Step 3: Open index.js file and write the following code to create a server.
Node
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(cors()); // Add this line to enable CORS
// Endpoint to receive username and password
app.post('/login', (req, res) => {
const { username, password } = req.body;
if (username === 'admin' && password === 'password') {
res.status(200).json({ message: 'Login successful' });
} else {
res.status(401).json({ message: 'Invalid credentials' });
}
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 4: Run the server by running the following command in the terminal
node index.js
Steps to Create a React App and Installing Axios
Step 1: Create a new react app and enter into it by running the following commands provided below.
npx create-react-app axios-demo
cd axios-demo
Step 2: Install axios dependency by running the command provided below.
npm install axios
The updated Dependencies in package.json file of frontend will look like:
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.7",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
Project Structure(Frontend):

Example 1: Basic Approach with Inline Headers:
In this example, we will send basic auth without creating axios instance.
JavaScript
import React, { useState } from 'react';
import axios from 'axios';
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async () => {
try {
const response =
await axios.post('http://localhost:5000/login',
{ username, password });
setMessage(response.data.message);
} catch (error) {
console.error('Error logging in:', error);
setMessage('An error occurred');
}
};
return (
<div style={{ maxWidth: '500px', margin: '0 auto' }}>
<header style={{ padding: '20px 0px', color: "#224F63" }}>
<h1>Testing Username and Password</h1>
</header>
<div style={
{
display: 'flex',
flexDirection: 'column',
marginTop: '20px'
}}>
<input
type='text'
placeholder='Enter Username'
value={username}
onChange={(e) => setUsername(e.target.value)}
style={
{
padding: '20px',
marginBottom: '10px',
border: '1px solid #ccc',
borderRadius: '5px',
fontSize: '16px'
}}
/>
<input
type='password'
placeholder='Enter Password'
value={password}
onChange={(e) => setPassword(e.target.value)}
style={
{
padding: '20px',
marginBottom: '10px',
border: '1px solid #ccc',
borderRadius: '5px',
fontSize: '16px'
}}
/>
<button
onClick={handleSubmit}
style={
{
padding: '20px 20px',
backgroundColor: '#0C73A1',
color: 'white',
border: 'none',
borderRadius: '5px',
cursor: 'pointer',
fontSize: '16px'
}}>
Submit
</button>
{message && <p>{message}</p>}
</div>
</div>
);
}
export default App;
Output: Run the following command to start the server.
npm start

Example 2: Creating an instance of Axios:
In this approach, we will create an instance of Axios and export it. We will import it whenever want to send any requests.
JavaScript
// src/App.js
import React, { useState } from 'react';
import axios from './axios';
function App() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [message, setMessage] = useState('');
const handleSubmit = async () => {
try {
const response =
await axios.post('/login',
{ username, password });
setMessage(response.data.message);
} catch (error) {
console.error('Error logging in:', error);
setMessage('An error occurred');
}
};
return (
<div style=
{{ maxWidth: '500px', margin: '0 auto' }}>
<header style=
{{ padding: '20px 0px', color: "#224F63" }}>
<h1>Sending Basic Auth With Axios</h1>
</header>
<div style={
{
display: 'flex',
flexDirection: 'column',
marginTop: '20px'
}}>
<input
type='text'
placeholder='Enter Username'
value={username}
onChange={(e) => setUsername(e.target.value)}
style={
{
padding: '20px',
marginBottom: '10px',
border: '1px solid #ccc',
borderRadius: '5px',
fontSize: '16px'
}}
/>
<input
type='password'
placeholder='Enter Password'
value={password}
onChange={(e) => setPassword(e.target.value)}
style={
{
padding: '20px', marginBottom: '10px',
border: '1px solid #ccc', borderRadius: '5px',
fontSize: '16px'
}}
/>
<button
onClick={handleSubmit}
style={
{
padding: '20px 20px', backgroundColor: '#0C73A1',
color: 'white', border: 'none', borderRadius: '5px',
cursor: 'pointer', fontSize: '16px'
}}>
Submit
</button>
{message && <p>{message}</p>}
</div>
</div>
);
}
export default App;
JavaScript
// src/axios.js
import axios from 'axios';
const instance = axios.create({
baseURL: 'http://localhost:5000',
headers: {
'Content-Type': 'application/json',
},
});
export default instance;
Run the following command to start the server.
npm start
Output:
output
Similar Reads
How To Build a Basic CRUD App With Node and React ?
In this article, we will explore how to build a simple CRUD (Create, Read, Update, Delete) application using Node.js for the backend and React for the frontend. Additionally, we will integrate MongoDB as the database to store our data. Preview of final output: App functionalityCreate a new student (
11 min read
How To Connect Node with React?
To connect Node with React, we use React for the frontend (what users see) and Node.js for the backend (where the server logic lives). The frontend sends requests to the backend, and the backend responds with data or actions. There are many ways to connect React with Node.js, like using Axios or Fet
4 min read
How to authenticate firebase with GitHub in ReactJS ?
The following approach covers how to authenticate firebase with GitHub in react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React app using the following command: npx create-react-app gfgappStep 2: After creating your project fo
3 min read
How to send one or more files to an API using axios in ReactJS?
Assuming that you want to send multiple files from the front-end, i.e., the React app, to the server using Axios. For that, there are two approaches as shown below: Send multiple requests while attaching a single file in each request.Send a single request while attaching multiple files in that reque
3 min read
How to Build a REST API with Next.js 13?
Next.js is the most widely used React framework. Next.js 13.2 introduced a new file-based routing mechanism, called App Router, for building React frontend and serverless backend. In this article, we will be building a simple REST API using Next.js Route Handlers Table of Content Next.js Route Handl
7 min read
How To Build Node.js Authentication System With MySQL?
Node.js is an open-source server-side JavaScript runtime environment established to develop server-side applications. The first task can be an implementation of an authentication system, this is one of the most frequently used processes in web development. In this article, we are going to learn how
4 min read
How to manage global state in a React application?
Global state refers to data that is accessible across multiple components in a React application. Unlike the local state, which is confined to a single component, the global state can be accessed and modified from anywhere in the component tree. In this article, we will explore the following approac
7 min read
How To Connect MongoDB with ReactJS?
MongoDB is a popular NoSQL database known for its scalability, flexibility, and high performance. When building modern web applications with ReactJS, itâs common to connect your frontend with a backend server that interacts with a database like MongoDB. PrerequisiteReact JSNode JSMongo DBApproach to
5 min read
How to authenticate phone number using firebase in ReactJS ?
User authentication is a critical aspect of many web applications, and phone number authentication has become increasingly popular for its convenience and security. Firebase, a powerful platform developed by Google, offers various authentication methods, including phone number authentication. Prereq
3 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Re
4 min read