Authentication Service
Let’s learn to create the necessary services that provide authentication for the whole application.
We'll cover the following
Many approaches can be used to integrate the API into the frontend, but the ones that we chose will depend on the scale of our project. For our purposes, it’s better to isolate the API integration and transfer it to the application components using abstract services.
Services
The services approach scales exceptionally well with different applications and makes those same applications easier to maintain and debug. In the existing services
directory, we’ll create these three files:
- The
services/auth.header.js
file handles the common header that must be presented in all HTTP requests. - The
services/auth.service.js
file handles authentication services, such as sign-up, login, and logout. - The
services/user.service.js
file handles any other service related to the user profile, such as uploading a file.
Header service
In the services/auth.header.js
directory, we’ll implement the required headers for the authenticated requests.
export default function authHeader() {
/**
* Get the current user stored in the localStorage and parse it as a JSON
* so we can access the user object easily in JavaScript
*/
const user = JSON.parse(localStorage.getItem("user"));
/**
* Check if the user is undefined (exists) and has a token
* so you can use that token in the authenticated requests to the server
* If there is no user, then return an empty object and the server should reject the request
*/
if (user && user.token) {
return { "x-access-token": user.token };
} else {
return {};
}
}
Auth service
We implement the actual service of the authentication in services/auth.service.js
. We use axios
as the HTTP client in the frontend.
-
We import
axios
and define the API endpoint, like this:import axios from "axios"; // HTTP Client const API_URL = "http://localhost:4000/api"; // The API endpoint to communicate with the server
-
We implement the signup service, like this:
/** * Handles the signup HTTP request to add a new user to the database * The data needed for each user is First Name, Last Name, Username, Email, and Password */ const signup = ({ firstName, lastName, username, email, password }) => { return axios.post(`${API_URL}/signup/`, { firstName, lastName, username, email, password, }); };
Note: The sign-up request has no headers because it’s a public endpoint. This means that anyone can register a new user in the application.
-
We implement the login service, like this:
/** * Handles the login HTTP request to access your user profile * The data needed for each user is the username or email along with the password */ const login = ({ emailOrUsername, password }) => { return axios .post(`${API_URL}/login/`, { emailOrUsername, password }) .then((res) => { /** * If successfully logged in, store the user data, including the token, in the localStorage */ localStorage.setItem("user", JSON.stringify(res.data)); return res.data; }); };
We use the
localStorage
to store the user data, including the user token. That way, we can access the token through JavaScript and keep the data saved, even after refreshing the page or restarting the browser. -
We implement the logout service, like this:
const logout = () => { localStorage.removeItem("user"); };
For now, we remove the token from the localStorage
on the client side because we don’t need any additional processing on the server side.
-
We may need a service to get the current user from the
localStorage
:const getCurrentUser = () => { return JSON.parse(localStorage.getItem("user")); };
While there may be additional services that might be useful for our application, we’ve covered all of the authentication services we need for now.
Here’s the complete code for authentication headers and services:
Get hands-on with 1200+ tech skills courses.