I am in the process of developing a backend application that necessitates user authentication. Within this project, I'm utilizing 2 external APIs:
- API A: responsible for managing user accounts and sessions
- API B: utilized for executing CRUD operations on a separate database unrelated to the users' database
An issue arises when I want to prevent unauthorized calls to API B when a user's session is invalid. To address this, I created specific API endpoints in Next (located under pages/api
) designed to execute the following tasks:
- Verify the session's validity against API A
- If the session is deemed valid, proceed to step 3; if not, redirect the user to the
/login
page - Execute the necessary call to API B
The functionality works correctly when the session remains valid, but it encounters failure when the session is invalid.
I attempted using
res.redirect(307, '/login').end()
and
res.writeHead(307, { Location: '/login' }).end()
Unfortunately, neither solution proved successful. Even explicitly specifying the entire path (http://localhost:3000/login
) failed to resolve the issue. Strangely enough, I can achieve successful redirection to the /login
page by directly accessing the URL via a browser (GET http://localhost:3000/api/data
). The problem only seems to arise when making requests through Axios within a React component.
Any suggestions on how I can rectify this situation?