This project demonstrates how to implement user authentication in a React application using React Router and fetch API. The implementation supports both login and signup modes, handling server communication, token storage, and expiration management.
- Dynamic Authentication Modes: Handle both login and signup flows based on URL parameters.
- Form Data Handling: Process user inputs and validate data.
- Server Communication: Send POST requests to the server with
fetch. - JWT Token Management: Store tokens in
localStoragewith expiration time. - Error Handling: Handle HTTP status codes like
401,422, and500. - Redirection: Redirect users to the home page after successful authentication.
This component renders the authentication form (AuthForm) and connects it to the logic defined in the action function.
import { redirect } from "react-router-dom";
import AuthForm from "../components/AuthForm";
function AuthenticationPage() {
return <AuthForm />;
}
export default AuthenticationPage;Handles form submission, validates data, communicates with the server, and manages token storage.
-
URL Parameter Handling:
const searchParams = new URL(request.url).searchParams; const mode = searchParams.get("mode") || "login";
-
Mode Validation:
if (mode !== "login" && mode !== "signup") { throw new Response(JSON.stringify({ message: "Invalid request" }), { status: 422, }); }
-
Form Data Processing:
const data = await request.formData(); const authData = { email: data.get("email"), password: data.get("password"), };
-
Server Request:
const response = await fetch(`http://localhost:8080/${mode}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(authData), });
-
Response Handling:
if (response.status === 422 || response.status === 401) { return response; } if (!response.ok) { throw new Response(JSON.stringify({ message: "Something went wrong" }), { status: 500, }); }
-
Token Management:
const resData = await response.json(); const token = resData.token; localStorage.setItem("token", token); const expiration = new Date(); expiration.setHours(expiration.getHours() + 1); localStorage.setItem("expiration", expiration.toISOString());
-
Redirect on Success:
return redirect("/");
- The server returns a JWT token, which is stored in
localStorageto maintain user authentication state. - When making subsequent requests, the token is included in the
Authorizationheader with theBearerscheme:Authorization: Bearer <token>
- 422: Indicates invalid request data, such as an incorrect email format or short password.
- 401: Indicates authentication failure, such as an invalid email or password.
- 500: Indicates an unexpected server error.
- Clone the repository:
git clone https://github.com/JinLee0811/miniBlog_with_Auth.git
- Install dependencies:
npm install
- Run the development server:
npm start
- React Router Documentation: https://reactrouter.com
- JWT Documentation: https://jwt.io
- Fetch API: MDN Docs
For the complete implementation, check the repository: GitHub