#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 Signup

Adding signup means taking the email and password from your React form, sending them to the authentication server in a POST request, and handling the response: a token and user details on success, or an error message on failure. It is usually the first real network call in an auth flow, and it sets the pattern that login will follow.

What the request and response contain

Most signup endpoints expect a JSON body with at least an email and a password. A successful reply usually returns a status of 201 Created or 200 OK with a token that proves who the user is, and often the user's id. A failed reply uses a 4xx status, for example 409 Conflict when the email is already registered or 400 Bad Request when the password is too short, plus a message explaining why.

Writing the submit handler

const API_URL = import.meta.env.VITE_API_URL;

async function handleSubmit(event) {
  event.preventDefault();
  setError(null);
  setIsLoading(true);

  try {
    const response = await fetch(`${API_URL}/signup`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, password }),
    });

    const data = await response.json();

    if (!response.ok) {
      throw new Error(data.message || 'Signup failed');
    }

    onAuthenticated(data.token, data.userId);
  } catch (err) {
    setError(err.message);
  } finally {
    setIsLoading(false);
  }
}

Here setError and setIsLoading come from two extra useState hooks in the form component, and onAuthenticated is a function passed in through props, often from a context provider, that saves the token so the rest of the app knows the user is logged in.

Why checking response.ok matters

fetch only rejects when the request could not be made at all, for example when the network is down. A server reply of 409 or 500 still counts as a completed request, so the promise resolves. If you skip the response.ok check, your code will treat an error message as if it were a valid account and try to read a token that does not exist. Throwing inside the try block sends both kinds of failure to the same catch.

Guarding the form while it works

  • Disable the submit button while isLoading is true so a double click does not create two requests.
  • Change the button text to something like "Creating account..." so the user knows something is happening.
  • Keep browser checks such as type="email" and minLength, but treat them as convenience only. The server must validate again, because anyone can send a request without your form.

Pitfall: where the token ends up

After signup, it is tempting to drop the token in localStorage and move on. That works and survives page reloads, but any script running on your page can read it, so a cross-site scripting bug would expose it. Some apps prefer the server to set an httpOnly cookie that JavaScript cannot read. Whichever you choose, store the token in one place only, also keep it in React state or context for the current session, and never log it to the console. If the server returns an expiry time, store that too so you can log the user out when the token is no longer valid.

Using one handler for both modes

Since the form already has an isLogin flag, you can choose the endpoint with a single line: const path = isLogin ? '/login' : '/signup';. The body, headers and error handling stay the same.

Key points

Send credentials as JSON with a POST request, check response.ok before trusting the reply, show a loading state, and pass the token to one central place. With signup working, the next job is presenting clear feedback when it fails.

Ready to master real-world web development?

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

Explore Course