Support Online
Skip to main content

Setting Up Token-Based Authentication in React Applications

By adding login authentication to your React application, you can protect private pages and make user sessions permanent.
In this guide, you will learn the token-based authentication system step by step using sessionStorage and localStorage.

📘 What You Will Learn in This Guide

In this guide, you'll learn how to add token-based login verification to your React project.
When the user is not logged in, you will show the login interface without page redirection and protect the session with browser data.


⚙️ Prerequisites

  • Node.js and npm must be installed
  • An empty React project created with create-react-app
  • Basic knowledge of JavaScript, HTML and CSS
  • Form management and API call basics in React

1️⃣ Installing Home Page Components

A. Installing React Router
npm install react-router-dom

This command installs the react-router-dom library required for browser redirects.

B. Creating Dashboard and Preferences

mkdir src/components/Dashboard
mkdir src/components/Preferences
Dashboard.js

import React from 'react';
export default function Dashboard() {
return <h2>Yönetim Paneli</h2>;
}
Preferences.js

import React from 'react';
export default function Preferences() {
return <h2>Ayarlar</h2>;
}

These two components are special pages that cannot be accessed without login.

C. Defining Routes in App.js

import { BrowserRouter, Route, Switch } from 'react-router-dom';
import Dashboard from '../Dashboard/Dashboard';
import Preferences from '../Preferences/Preferences';
import './App.css';

function App() {
return (
<div className="uygulama-sarmalayici">
<h1>GenixNode Uygulaması</h1>
<BrowserRouter>
<Switch>
<Route path="/dashboard" component=&#123;Dashboard&#125;/>
<Route path="/preferences" component=&#123;Preferences&#125;/>
</Switch>
</BrowserRouter>
</div>
);
}

export default App;

2️⃣ Login Component and Token Control

Login.js

import React from 'react';
import './Login.css';

export default function Login(&#123; setToken &#125;) {
return (
<div className="login-wrapper">
<h1>Lütfen Giriş Yapın</h1>
<form>
<label>
<p>Kullanıcı Adı</p>
<input type="text" />
</label>
<label>
<p>Şifre</p>
<input type="password" />
</label>
<div><button type="submit">Giriş Yap</button></div>
</form>
</div>
);
}
Login.css

.login-wrapper {
display: flex;
flex-direction: column;
align-items: center;
}

The form centers the page, providing a minimalist appearance.


3️⃣ Fake API Providing Tokens (Node.js / Express)

Server setup:

npm install --save-dev express cors

server.js


const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

app.post('/login', (req, res) => {
res.send({ token: 'genixnode-guvenli-token-12345' });
});

app.listen(8080, () =>
console.log('API çalışıyor: http://localhost:8080/login')
);

This API returns a test token to the POST request from the user.


4️⃣ Connecting API to Login Page


async function loginUser(credentials) {
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(credentials)
}).then(res => res.json());
}

const handleSubmit = async (e) => {
e.preventDefault();
const token = await loginUser({ username, password });
setToken(token);
};

These functions send the form data to the API and store the returned token.


5️⃣ Token Persistence – useToken Hook

useToken.js

import &#123; useState &#125; from 'react';

export default function useToken() {
const getToken = () => {
const tokenString = sessionStorage.getItem('token');
const userToken = JSON.parse(tokenString);
return userToken?.token;
};

const [token, setToken] = useState(getToken());

const saveToken = (userToken) => {
sessionStorage.setItem('token', JSON.stringify(userToken));
setToken(userToken.token);
};

return { token, setToken: saveToken };
}

This special Hook stores the token and keeps it synchronized with the React state.

If you use localStorage instead of sessionStorage, the session remains even if the browser closes.


🙋‍♀️ Frequently Asked Questions (FAQ)

  1. What is the difference between sessionStorage and localStorage?

SessionStorage is tab-based; localStorage is persistent and shared across tabs.

  1. Why is HTTP-Only Cookie more secure?

Because JavaScript can't access it; Provides protection against XSS attacks.

  1. What changes if I use React Router v6?

Routes are used instead of switches, and element props are used instead of components.

  1. What happens if the token expires?

API requests return errors; The user must log in again.

  1. Is this system safe?

It is for training and demo purposes. In a production environment, server-side control with HTTP-Only cookies or JWT is recommended.


🎯 Result

Now you know how to add token-based authentication to your React app. When the user is not logged in, you can display the login interface and manage token storage strategies.

💡 You can test this structure in minutes on the GenixNode infrastructure and publish your React project instantly.