#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
Authentication

Using Tokens

Once the login endpoint returns a token, the frontend has three jobs: keep the token somewhere it can reach, attach it to every request that needs authentication, and react when the server says the token is no longer valid. On the backend, a small piece of middleware checks the token before protected routes run. This lesson walks through both sides for a React app talking to an Express API.

Keeping the token after login

The simplest approach is to store the token in React state, usually inside a context so any component can read it. State disappears on a page refresh, so many apps also copy the token into localStorage and read it back when the app starts. Be aware of the trade-off: any script running on your page, including injected code from a cross-site scripting bug, can read localStorage. Apps that need stronger protection let the server set the token in an httpOnly cookie instead, which JavaScript cannot read at all.

Sending the token with requests

The standard place for a token is the Authorization header using the Bearer scheme. Writing a small helper keeps you from repeating this in every component.

export async function apiFetch(path, token, options = {}) {
  const response = await fetch(path, {
    ...options,
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
      Authorization: `Bearer ${token}`
    }
  });
  if (response.status === 401) {
    throw new Error('SESSION_EXPIRED');
  }
  return response.json();
}

A component can call apiFetch('/api/orders', token) and get parsed data back, or catch the special error and send the user to the login screen.

Checking the token on the server

On the Express side, protected routes share one middleware function. It pulls the token out of the header, verifies it, and attaches the user details to req so later handlers can use them.

const jwt = require('jsonwebtoken');

function requireAuth(req, res, next) {
  const header = req.get('Authorization') || '';
  const [scheme, token] = header.split(' ');
  if (scheme !== 'Bearer' || !token) {
    return res.status(401).json({ error: 'Missing token' });
  }
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid or expired token' });
  }
}

app.get('/api/orders', requireAuth, (req, res) => {
  res.json(findOrdersFor(req.user.sub));
});

Pay attention to the difference between the two status codes. Reply with 401 Unauthorized when the token is missing, malformed or expired, because the client needs to log in again. Reply with 403 Forbidden when the token is valid but the user lacks permission, such as a regular user calling an admin route. The frontend can then treat them differently: a 401 clears the session and opens the login page, while a 403 shows a "you do not have access" message and keeps the user signed in.

Where people go wrong

A classic error is trusting a user ID sent in the request body or URL instead of the one inside the verified token. If a route reads req.body.userId, any logged-in person can edit that value and act as someone else. Always take identity from req.user, which only the middleware sets.

Another slip is forgetting to clear the token on logout or on a 401 response. The UI keeps showing "logged in" while every request fails. Clear state and storage together in one logout function and call it from both places.

Expired tokens deserve a smooth experience too. If your API issues refresh tokens, the shared fetch helper can catch the first 401, request a new access token once, and retry the original call. Limit this to a single retry so a broken refresh token cannot cause an endless loop of requests.

In short

Store the token in one place, send it in the Authorization header through a shared helper, verify it in middleware, and treat a 401 as a signal to log the user out cleanly.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course