21 hours ago

Why does the local redirect send an unexpected GET request?

My objective is to help solve the issue on a site that I am creating. The site requires the following behavior: - When a user attempts to access the /home page without authentication, they should be redirected to the /login page. - After successfully logging in through the /login page, the user will receive a session cookie and be redirected to the /home page. - If a user returns to the /login page with a valid session cookie, they should be automatically redirected to the /home page. I am using Node.js with Express and have included the current server-side code. The function to authenticate the user is preventing unauthorized access to the /home page. The user-side code includes a function that triggered by an onclick property on a button. The issue I am facing is that upon receiving a 200 response with a cookie after sending a POST request to /login, the browser automatically sends both GET requests to the /home and /login pages. This behavior results in the /login page request being prioritized, and the browser interprets the GET /home as a 308 status while the server fails to receive any requests to /home. Even after removing the window load event listener, the same issue persists. Modifying the server-side code to redirect to the /login page also does not solve the problem. The browser keeps displaying a sequence of GET requests to /home and /login pages, and the server fails to log anything. What could be the issue here, and how can it be resolved?
21 hours ago
Verified Answer
The issue seems to be caused by the fact that the POST request triggered by the login function in the user-side code returns a response with a status of 200 but does not wait for the cookie to be set before sending a GET request to the /home page. Therefore, when the user is immediately redirected to /home, the browser also sends a GET request to /login, which then causes a never-ending loop of requests and redirections. A possible solution is to use async/await in the login function to wait for the response with the session cookie to be returned before redirecting the user to /home. Here's an updated version of the login function:
try {
    const response = await fetch('/login', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      body: JSON.stringify({
        'id': id,
        'password': password

    if (response.status === 401) {
      // display error message
    } else if (response.status === 200) {
      await response.text();
  } catch (error) {
    // handle error
By using async/await in the login function, we ensure that the function waits for the response with the session cookie to be returned before redirecting the user to /home. This should prevent the never-ending loop of requests and redirections.