Home >Backend Development >Python Tutorial >How Do I Redirect Users After Login Using JavaScript Fetch API?
Using the JavaScript code below, the authentication token is first obtained using the firebase.auth() method. A POST request is then made to the FastAPI backend. If the token is valid, a redirect response is returned. However, the user is not actually redirected, and the original page remains loaded.
<code class="javascript">function loginGoogle() { var provider = new firebase.auth.GoogleAuthProvider(); firebase.auth() .signInWithPopup(provider) .then((result) => { // ... }) .catch((error) => { // Handle Errors here. // ... }); firebase.auth().currentUser.getIdToken(true).then((idToken) => { // ... const headers = new Headers({ 'x-auth-token': idToken }); const request = new Request('http://localhost:8000/login', { method: 'POST', headers: headers }); fetch(request) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error)); }); }</code>
By default, the fetch() method in JavaScript sets the redirect mode to follow, meaning that the user will not be redirected to a new page but instead the redirect response will be handled automatically behind the scenes. If you want to manually handle the redirect, you can set the redirect mode to manual and then use the Response.redirected and Response.url properties to obtain the redirect URL and redirect the user yourself to that URL using window.location.href or window.location.replace().
Instead of returning a RedirectResponse from the server, you can return a normal JSON response with the URL included in the JSON object. On the client side, check if the JSON object returned from the server includes the url key, and if so, retrieve its value and redirect the user to that URL using window.location.href or window.location.replace().