#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

Adding User Login

Adding user login means building a form where an existing user enters their email and password, sending those details to your authentication backend, and updating the app once the server confirms who they are. In a React app it sits right after signup: the signup flow creates the account, and login lets that person come back later.

What the login request looks like

The browser never decides whether a password is correct. It only collects the credentials and sends them over HTTPS to an endpoint such as POST /api/login. The server looks up the user, compares the password against the stored hash, and replies with either an error or a success response that usually contains a token or sets a session cookie.

On the React side you need three pieces of state: the form values, a loading flag, and an error message to show if the attempt fails.

import { useState } from 'react';

function LoginForm({ onLoggedIn }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    setError('');
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ email, password }),
      });
      const data = await res.json();
      if (!res.ok) throw new Error(data.message || 'Login failed');
      onLoggedIn(data);
    } catch (err) {
      setError(err.message);
    } finally {
      setLoading(false);
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input type="email" value={email}
        onChange={(e) => setEmail(e.target.value)} required />
      <input type="password" value={password}
        onChange={(e) => setPassword(e.target.value)} required />
      {error && <p role="alert">{error}</p>}
      <button disabled={loading}>
        {loading ? 'Signing in...' : 'Log in'}
      </button>
    </form>
  );
}

Reusing the signup logic

Signup and login usually differ only in the URL and the fields sent. Rather than copying the whole handler, many apps write one function such as authenticate(mode, credentials) that picks the endpoint based on mode. The form component then switches a single isLogin flag to change the heading, button text and target URL.

After the server says yes

A successful response should change what the user sees. Typical steps are:

  1. Store the returned user data or token somewhere the app can reach, such as context or a state manager.
  2. Redirect to a protected page, for example with useNavigate() from React Router.
  3. Swap the "Log in" link in the navigation for a "Log out" button.

How and where to keep the token safely is covered in the next lesson on tokens, so for now passing the data up through onLoggedIn is enough.

Common mistakes with login forms

  • Checking only for network errors. fetch does not reject on a 401 or 400. You must test res.ok yourself, or a wrong password will look like a successful login.
  • Revealing too much. Show a general message like "Email or password is incorrect" instead of "No account with this email". Specific messages help attackers find valid accounts.
  • Allowing double submits. Disable the button while the request is in flight so a fast double click does not send two requests.
  • Logging the password. Never print the password to the console or keep it in state after the request finishes longer than needed.

Checklist before moving on

  • The form prevents the default page reload and sends JSON to the login endpoint.
  • Non-2xx responses are treated as failures and shown to the user.
  • Loading state disables the button and gives visible feedback.
  • On success, the app records the logged-in user and navigates away from the form.

Ready to master real-world web development?

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

Explore Course