Redirecting with response headers in Next.js

Objective: The Goal: Clicking a button on a page should send a request to the controller. The controller will then set a cookie, and upon receiving the response, redirect the page to another page, such as the about page.

Directly Calling API route from the browser: Using this code, I can access the api route directly from the browser as expected.

However, when trying to implement the same process with a button click, the cookies are set but the redirection to the about page does not occur, resulting in a 307 Response error.

My API is hosted on the same server using Next.js.

I could use a router to implement this, but I prefer to utilize response header redirect. What am I missing here? Thank you.

// home.tsx
'use client';
export default function Home() {
    const handleSet = () => {
        (async () => {
            await fetch('http://localhost:3000/api/test-path');
        })();
    };
    return (
        <main className="min-h-screen">
            <p>Home page</p>

            <button className="btn btn-primary" onClick={handleSet}>
                Set cookies
            </button>
        </main>
    );
}

Answer №1

The handleSet event handler utilizes the fetch api to make a request, which is completely browser-independent and not tied to the document location of the browser. As a result, there won't be an automatic redirect triggered within the browser. Any redirection that is desired must be implemented manually.

For example:

//[...]
await fetch(
  'http://example.com/api/test-path', 
  {redirect:"manual"}
).then((response)=>{ 
  const redirectUri = response.headers.get("Location");
  //if Location header exists, perform redirect ...
  redirectUri && document.location.href = redirectUri
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Typescript: Cannot find reference to @viewChild

I attempted to use the select() method in tabs.ts based on the Ionic Tabs documentation. However, upon running it, I encountered an error stating that "select is undefined". Upon further investigation, I realized that my viewChild was empty or undefined wh ...

Adjust the checked state of the checkbox based on the outcome of the promise's data

Whenever the checkbox is clicked and the resolved data in a promise is false, I want the checkbox to remain unchecked. If the data is true, then the checkbox should be checked. I have set up a codesandbox for this purpose. This example utilizes react and ...

React Component not displaying properly when used inside a map iteration

I am currently working on rendering multiple components using the .map method on an array with specific content. Although I can't find any errors in the console, the component is not appearing in the DOM as expected. I attempted to set subHeader to nu ...

Passing a particular method of a specific instance as an argument

I am interested in creating a class that allows me to specify "For instance a1 of A, you will call the function computeValue() of a specific instance b1 of B when the value is needed". It's important for me to indicate which method of which instance w ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

Updating data in Angular reactive forms using asynchronous dropdowns

I am currently developing an Angular application and have encountered an issue that I am unable to resolve by solely reading the documentation. One of the components in my application is responsible for displaying a form: https://i.stack.imgur.com/p5KEU. ...

Exploring the implementation of Chain Map or Chain Filter within an Angular Http request that delivers a promise

I have a dataset in JSON format that I am working with, and I need to filter out specific key values using lodash. I want to reject multiple keys that I don't need. My initial approach is to either chain the map function and then use the reject funct ...

Using Typescript: How to access a variable beyond the scope of a loop

After creating an array, I need to access the elements outside of the loop. I am aware that they are not in the scope and using 'this.' before them does not grant access. colIdx = colIdx + this.columns.findIndex(c => c.editable); this.focusIn ...

Implement a feature in JavaScript that highlights the current menu item

I'm currently developing a website at and have implemented a JavaScript feature to highlight the current menu item with an arrow. The issue I'm facing is that when users scroll through the page using the scrollbar instead of clicking on the men ...

Obtain identical socket event in two separate useEffect hooks

I am facing an issue where I want to access the same event in two different useEffect functions on the same page. Despite my attempts, it doesn't seem to work as expected. Below is what I have tried so far. I'm wondering if it's possible to ...

"Alert: Cautionary notification when utilizing server action in the latest version of Next.js

I keep receiving this warning message in my server-side console while using server actions: Warning: Cannot specify an encType or method for a form that specifies a function as the action. React provides those automatically and they will be overridden. Ho ...

The error message "TypeError: 'undefined' is not an object ('_this.props')" indicates that the property '_this

Having trouble solving this issue. Need assistance with evaluating 'this.props.speciesSelection.modalize' <BarcodeInput speciesSelection={this.props.speciesSelection} species={species[0]} barcode={{ manufacturerValue: ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

ng-view does not support ng-repeat rendering

I have a basic app using ng-view and ng-repeat. Initially, it worked fine without ng-view, but after switching to ng-view, the ng-repeat stopped functioning correctly. Oddly, when I clicked on the "menu" link, it displayed another set of $var instead of ch ...

Sending a PDF document and JSON data via an AJAX POST request

I'm attempting to send a PDF document along with some JSON data in string format using an AJAX method in jQuery to an ASP.NET WEB API (2). Below are my attempts that are not working: JAVASCRIPT: // Obtaining the authorization token works fine var hea ...

Tips for choosing and filtering the preferred object in ES6

Consider this array structure: const testData = [ { group: "Team1", info: [ { key: 123, person: "Alice", type: "Football" }, { key: 456, person: "Bob", type: " ...

The div container is not expanding to full width on mobile screens when using Next.js and Tailwind CSS

My goal is to make my div stretch or go full width similar to the table on my page. I have experimented with max-w-full, w-screen, and w-full, but the div is not extending all the way... https://i.stack.imgur.com/8BJnI.png This is the code for my page. ...

Iterate through JSON and dynamically populate data

My goal is to dynamically populate content by iterating through JSON data using jQuery. First, an Ajax request is made Then the data is looped through to create HTML tags dynamically A div container with the class "product-wrapper" is created for each J ...

Is it possible to have an Iframe that contains content but no src attribute?

During the process of troubleshooting jQuery code on their website (using the Chrome Developer Toolbar), I came across an interesting observation. I found that their examples were embedded within an Iframe: Here, for instance, there is a sample displayed ...