In our last session we have implemented a basic structure of login form where we call the auth service, to make an API call to our backend Rails API.
Now we modify and improve each of our files one by one.
We removed the try, catch blocks. Our current auth service file look like this:
import type { LoginRequest } from "../types/auth";
export async function loginRequest(args: LoginRequest) {
const response = await fetch(import.meta.env['VITE_API_BASE_URL'] + "/api/v1/auth/login", {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
// Essential for receiving and sending session cookies cross-origin
credentials: 'include',
body: JSON.stringify(args)
});
const data = await response.json();
return data;
}
Now let’s handle the next issue in authService.ts: HTTP error responses.
Currently, even when the backend returns 401 Unauthorized, your function parses the response and returns it as if the request succeeded.
Step 2: Check response.ok
The Fetch API provides response.ok:
truefor successful HTTP responses (status 200-299).falsefor responses such as 401, 403, and 422.
After parsing the response JSON, add this check:
if (!response.ok) {
throw new Error(data.errors?.[0] ?? "Login failed");
}
Our function will now behave like this:
- Login succeeds: returns the response data.
- Login fails with an HTTP error: throws an error with the backend’s message.
- Network failure: the Fetch API error propagates to the caller.
Why are we throwing the error?
Because the component calling loginRequest() should decide how to display the error to the user. The service should handle the API request, not React UI state.
A network error does not become "Login failed" automatically. There are two different paths:
1. Backend returns HTTP 401
fetch() receives the response successfully. Then response.ok is false, so your code executes: throw new Error(data.errors?.[0] ?? "Login failed");
2. Network failure
For example, the Rails server is stopped. fetch() itself rejects its Promise. Execution jumps directly to the caller’s catch block. Your response.ok check is never reached.
So the component calling loginRequest() needs to catch both errors.
Let’s update the handleLogin function from LoginForm
Update LoginForm with:
const handleLogin = async (event: React.SubmitEvent<HTMLFormElement>) => {
event.preventDefault();
setLoading(true);
setError([]);
....
....
try {
await loginRequest(params);
alert('Logged in successfully');
// props.setTasks(data);
} catch (error) {
setError([error instanceof Error ? error.message : "Something went wrong"])
} finally {
setLoading(false);
}
}
With newer React TypeScript definitions (@types/react 19.2.10+), FormEvent is deprecated in favour of SubmitEvent. Our React.SubmitEvent<HTMLFormElement> is the appropriate type.
Understand these three things
await loginRequest(params)waits for the API response.catchhandles both HTTP errors thrown by our service and network errors.finallyexecutes whether the request succeeds or fails. That’s where we reset the loading state.
Verify the login response
Before connecting the access token to App.tsx, let’s verify the actual response structure.
do this:
- Open your browser’s Developer Tools → Network.
- Submit the login form.
- Select the
/api/v1/auth/loginrequest. - Open its Response tab.
Check whether the response has a top-level data property or whether access_token is directly at the top level.
I get Reponse as:
{
"data": {
"access_token": "eyJhbGciOiJIUzI1NiJ9.ey......",
"expires_in": 600,
"token_type": "Bearer",
"user": {
"id": 1,
"email": "test@example.com"
}
}
}
The response matches your existing LoginResponse type. The access token is inside response.data.access_token
In authService.ts, update the import:
import type { LoginRequest, LoginResponse } from "../types/auth";
Then update the function signature:
export async function loginRequest(
args: LoginRequest
): Promise<LoginResponse> {
Finally, change the return statement:
return data as LoginResponse;
The as LoginResponse tells TypeScript to treat the parsed JSON as this response structure. It does not validate the JSON at runtime.
Why are we doing this?
When you call: const response = await loginRequest(params);
TypeScript will now understand that:
response.data.access_token
response.data.user
response.data.expires_in
are available.
Next, we’ll pass the access token from LoginForm to App.tsx and store it in React state.
