Skip to content

Authentication Flow

Overview

Implementing authentication ensures secure access to protected resources in your application. In this section, we detail the process of creating a robust authentication flow.


Steps to Implement Authentication

Step 1: Create Login and Signup Pages

Create Login.jsx and Signup.jsx components inside the features/auth/pages/ directory:

// Login.jsx
import React, { useState } from "react";
import api from "../../shared/api";

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = async () => {
    try {
      const response = await api.post("/auth/login", { email, password });
      localStorage.setItem("token", response.data.token);
      alert("Login successful!");
    } catch (error) {
      console.error("Login Error:", error);
    }
  };

  return (
    <div>
      <h1>Login</h1>
      <input
        type="email"
        placeholder="Email"
        value={email}
        onChange={(e) => setEmail(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button onClick={handleLogin}>Login</button>
    </div>
  );
};

export default Login;

Step 2: Protect API Requests

Add a request interceptor in your Axios instance (api.js) to include the authentication token:

api.interceptors.request.use(
  (config) => {
    config.headers["Authorization"] = `Bearer ${localStorage.getItem("token")}`;
    return config;
  },
  (error) => Promise.reject(error)
);

Step 3: Handle Token Expiry

Implement token expiration logic and prompt users to log in again if the token is invalid:

api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response && error.response.status === 401) {
      alert("Session expired. Please log in again.");
      localStorage.removeItem("token");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);