Skip to Content

How do I use login API in React?

How do I use login API in React?

Authentication is an essential part of most web applications. Implementing a login system allows you to identify users and control access to certain pages and features. In React apps, authentication is typically handled via an API that connects to a back-end service managing user accounts.

In this comprehensive guide, we’ll explore how to build a login system in React using a JSON Web Token (JWT) based API. We’ll look at setting up the API, creating React components for registration and login, protecting routes, and more.

By the end, you’ll understand how to allow users to sign up, log in, and access protected resources in a React app. Let’s get started!

Setting Up the API

Our React app needs to communicate with a back-end API that can register users, authenticate logins, and return JWTs.

There are a few different ways we could create this API:

– Build our own Node/Express API from scratch. This gives us full control but requires more effort.

– Use a third-party authentication service like Auth0 or Firebase Auth. Less work, but less customization.

– Use a pre-built open source solution like Node-JWT-Auth. Gives us a JWT API out of the box.

For this example, we’ll use Node-JWT-Auth – it provides a ready-made Express API supporting user registration, login, and JWT creation.

To set it up:

1. Create a new Node project:

“`
mkdir react-login-api
cd react-login-api
npm init -y
“`

2. Install Node-JWT-Auth:

“`
npm install node-jwt-auth
“`

3. Create a basic Express server:

“`js
// index.js

const express = require(‘express’);
const app = express();

app.get(‘/’, (req, res) => {
res.send(‘Hello World’);
});

app.listen(3000);
“`

4. Import and initialize Node-JWT-Auth – this will add routes for /auth/register and /auth/login:

“`js
// index.js

// …

const jwtAuth = require(‘node-jwt-auth’);

jwtAuth.init({
secretOrPrivateKey: ‘secretKey’
});

// …
“`

This gives us a basic API that can handle user registration and login.

To test it out, send a POST request to /auth/register with a new user’s email and password. This will return a JWT token we can use for authentication.

We can now build our React app on top of this API.

Creating the React App

Let’s set up a new React project:

“`
npx create-react-app react-login-demo
cd react-login-demo
“`

We’ll need to install some additional dependencies:

“`
npm install react-router-dom axios
“`

– react-router-dom: For routing and navigation
– axios: Making HTTP requests to our API

Inside src/, create these additional files:

– /components/LoginForm.js
– /components/RegisterForm.js
– /components/Protected.js
– /utils/Auth.js

We’ll build out each of these shortly.

Update App.js to include some basic routing:

“`jsx
// App.js

import { BrowserRouter, Routes, Route } from ‘react-router-dom’;

function App() {
return (


}>
} />
} />
} />



);
}
“`

This will give us some starter routes to build upon.

Register Form

Let’s allow users to create an account with our API.

Inside RegisterForm.js:

“`jsx
// RegisterForm.js

import { useState } from ‘react’;
import { useNavigate } from ‘react-router-dom’;
import axios from ‘axios’;

function RegisterForm() {

const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);

const navigate = useNavigate();

const register = async (e) => {
e.preventDefault();

try {
await axios.post(‘/auth/register’, {
email,
password
});
navigate(‘/login’);
} catch(err) {
console.log(err);
}

}

return (

setEmail(e.target.value)}
/>

setPassword(e.target.value)}
/>


);

}

export default RegisterForm;
“`

This provides a basic form to enter an email and password.

On submit, it will send a POST request to our API to register the user. If successful, we navigate to the login page.

Make sure the API is running, and test out registration!

Login Form

Now let’s allow registered users to log in.

Inside LoginForm.js:

“`jsx
// LoginForm.js

import { useState } from ‘react’;
import { useNavigate } from ‘react-router-dom’;
import axios from ‘axios’;

function LoginForm() {

const [email, setEmail] = useState(”);
const [password, setPassword] = useState(”);

const navigate = useNavigate();

const login = async (e) => {
e.preventDefault();

try {
const res = await axios.post(‘/auth/login’, {
email,
password
});
console.log(res.data);
navigate(‘/protected’);
} catch(err) {
console.log(err);
}

}

return (

setEmail(e.target.value)}
/>

setPassword(e.target.value)}
/>


);

}

export default LoginForm;
“`

This login form is very similar to the registration.

On submit, it will post the credentials to the /auth/login API endpoint. If successful, this returns a JWT token that we can use for authentication.

For now, we’re just logging the token to the console. Shortly, we’ll use it to keep users authenticated across requests.

Protected Routes

We want certain routes in our React app to be protected – i.e. only accessible to logged in users with a valid JWT.

Let’s create a Protected component that checks for a token before rendering:

“`jsx
// Protected.js

import { Navigate } from ‘react-router-dom’;

function Protected({ children }) {
// Check for JWT token here

if(!token) {
// Redirect to login if no token
return ;
}

return children;
}

export default Protected;
“`

This checks for a JWT token, and redirects to /login if none is found.

We can wrap any routes we want to protect inside this component:

“`jsx



}
/>
“`

Now let’s actually get the token.

Token Storage

When a user logs in, we need to store their JWT token locally so we can keep them authenticated across page reloads:

– LocalStorage – Can store data persistently in the browser
– Cookies – Also store data in browser
– React Context – Keep token in memory
– Redux – Manage token via global state

For this example, we’ll use LocalStorage for simplicity.

Inside /utils/Auth.js:

“`js
// Auth.js

export function setToken(token) {
localStorage.setItem(‘token’, token);
}

export function getToken() {
return localStorage.getItem(‘token’);
}

export function removeToken() {
localStorage.removeItem(‘token’);
}
“`

This provides a simple API to get, set, and remove the token in LocalStorage.

Now we can update our login request to store the token:

“`js
// LoginForm.js

// …

const login = async (e) => {

// …

const res = await axios.post(‘/auth/login’, {
email, password
});

setToken(res.data.token); // Store token
navigate(‘/protected’);

}
“`

And update Protected.js to check for the token:

“`js
// Protected.js

import { getToken } from ‘./utils/Auth’;

function Protected({ children }) {
const token = getToken(); // Get from LocalStorage

if(!token) {
return ;
}

return children;
}
“`

Now our Protected routes will redirect if the user has no JWT stored.

Access Token in Requests

So far we’re just storing the JWT – we also need to send it on requests to prove a user’s identity.

Axios can automatically include the token on all requests using the Authorization header.

Update main Axios instance:

“`js
// utils/api.js

import axios from ‘axios’;
import { getToken } from ‘./Auth’;

export default axios.create({
baseURL: ‘http://localhost:3000’,
headers: {
Authorization: `Bearer ${getToken()}`
}
});
“`

Now any requests using this instance will include the JWT.

For example:

“`js
import api from ‘./utils/api’;

api.get(‘/users’); // Includes token
“`

The API can verify the token to authenticate the user.

Logout

For a full login flow, we should allow users to logout as well.

This involves:

– Removing the JWT from storage
– Redirecting to the homepage

Let’s create a new Logout component:

“`jsx
// Logout.js

import { useEffect } from ‘react’;
import { useNavigate } from ‘react-router-dom’;
import { removeToken } from ‘./utils/Auth’;

export default function Logout() {

const navigate = useNavigate();

useEffect(() => {
removeToken();
navigate(‘/’);
}, []);

return

Logging out…

}
“`

It will run on mount, clear the token, and redirect.

Add it as a route:

“`jsx
} />
“`

Now users can log out by visiting this path.

Optionally, add a logout link to a Header:

“`jsx
function Header() {

return (

)

}
“`

And that wraps up a basic login flow!

Users can:

– Register new accounts
– Log in
– Access protected routes
– And log out

Next Steps

Some additional ideas to improve this:

– Use React Context for shared state instead of LocalStorage
– Store token expiration and refresh it
– Show login/logout in header based on auth status
– Create a Higher Order Component for protected routes
– Add password reset flow
– Secure back-end API
– More robust validation and error handling

This covers the core concepts for adding authentication to a React app!

Conclusion

Implementing login functionality is key for most web applications. By integrating with a JSON Web Token API, React apps can securely authenticate users.

The main steps are:

– Setting up a back-end API to handle registration, login, and generating JWTs
– Creating React forms to register users and log them in
– Storing JWTs locally and including them with requests
– Protecting routes and resources by verifying tokens
– Allowing users to easily log out

This provides the building blocks for full user authentication in React. There are many additional optimizations and features that can be added as well.

I hope this guide gave you a good overview of implementing a basic but complete login flow in React! Let me know if you have any other questions.