Part 62: Connecting Our Sign-In Form to the API with React

[Pages] Authentication

[Pages] Authentication

In our previous blog post, we set up the Sign-In page with controlled components to manage form input. Now, we're taking the next step: connecting our form to an API. Specifically, we'll make a POST request to authenticate the user and handle the response.

Understanding the API Request

To authenticate, we need to send a POST request to the endpoint "/auth/local" with the user's email (as "identifier") and password in the request body. A successful response will include a JSON web token, which is essential for user authentication.

Step 1: Modifying the fetchJson Utility

Before making our API call, let's enhance our existing fetchJson utility to handle POST requests with headers and a body.

Updating fetchJson

Explanation:

  • Options Parameter: We've added an options parameter to pass additional configurations like method, headers, and body.

  • Error Handling: If the response is not okay, an error is thrown using ApiError.

Step 2: Implementing the API Call on Form Submission

We'll modify our form submission handler to call the API using the updated fetchJson function.

Adding the API Call

Explanation:

  • Async Function: We've made handleSubmit asynchronous to await the response from fetchJson.

  • POST Request: The fetchJson call includes the method, headers, and body necessary for the API request.

  • Logging Response: We log the response to the console to verify the API call's success.

Step 3: Testing the API Request

To test, fill in the form with an email (e.g., "[email protected]envelope") and password (e.g., "Alice123"). On clicking "Sign In," check the console for the response, which should include a token and user details.

Handling Environment Variables

While we currently hard-code the API URL, it's important to know that environment variables in client-side code require a prefix like NEXT_PUBLIC. This ensures they are accessible in the browser. However, we'll keep the URL hardcoded for now as it will be changed later in our project.

Addressing Errors

Currently, incorrect credentials result in an unhandled error. In our next update, we'll focus on improving error handling by displaying user-friendly messages.

Conclusion

With these changes, our Sign-In form is now connected to the API, capable of authenticating users. In upcoming posts, we'll improve error handling and integrate the authentication process more deeply into our application. Stay tuned!

Last updated