Redirecting in Next.js from an API route

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:

  1. Verify the session's validity against API A
  2. If the session is deemed valid, proceed to step 3; if not, redirect the user to the /login page
  3. 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?

Answer №1

After receiving guidance from @juliomalves and @yqlim, I successfully implemented a manual redirect using the API's response.

Answer №2

Instead of using .end(), have you considered utilizing res.redirect(307, '/login')?

In my experience with Next.js versions 12 and 13, the following code snippet has worked effectively.


// /api/example.js

const handler = async function (req, res) {
  // custom logic
  if (failed)
    return res.redirect(307, '/login')
}

export default handler;

Answer №3

Encountered a similar issue and was able to resolve it using the code snippet below:

API

res.status(200).json({ success: "success" }) // Add this line at the end of the API to send a response

Page

import Router from 'next/router'
    
let res = await fetch('api', {
        method: 'POST', // or 'PUT'
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data),
    })
if (res.status == 200) {
   Router.push('/location')
}

The solution is correct as mentioned by @Jules Grenier, but I have provided an additional example for clarification.

Answer №4

To start the API request, a <form> must be used.

<fetch> cannot handle redirects.

Answer №5

One simple way to make this happen is by employing NextResponse.redirect. Take a look at the following example for reference.

return NextResponse.redirect(process.env.NEXT_PUBLIC_APP_URL + "/login", { status: 307 });

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

Arranging icons at the bottom of the post with a text box that changes dynamically

My challenge is that when the content in a box overflows, the box size increases and pushes the icons out of place. I want to ensure that the icons remain in a fixed position. This is how it currently looks: The comment, delete, and likes count end up on ...

Error: The middleware function is not recognized | Guide to Transitioning to React Redux Firebase v3

After utilizing these packages for my project, I encountered an error in middleware composition while creating a new react app with create-react-app. Below are the packages I have included. Can someone please help me identify what is missing here? HELP I ...

Tips for bypassing an argument using the POST method in NodeJS

Hey there! I started off by creating a question about passing over data using the GET method, but now I'm facing a new problem when trying to pass over data with the POST method. Below is my code snippet where things seem to be going wrong. My goal is ...

Using Node.js to Send Emails via API

I've been grappling with an issue for over a week while trying to develop a web application that sends welcome emails to new subscribers. Despite my API code working perfectly, I cannot seem to get any output on the console indicating success or failu ...

Is it possible to decrease the size of a div by scrolling both vertically and horizontally?

Can a div's height and width both be reduced at the same time while scrolling down a page? Let's say that as the user scrolls, the size of the div changes from 400px by 400px to 200px by 200px, all while remaining centered on the page. I've ...

Ways to incorporate sass:math into your vue.config.js file

While using vue-cli with Vue 2.6 and sass 1.49, I encountered errors in the console related to simple division calculations: Deprecation Warning: Using / for division outside of calc() is deprecated and will be removed in Dart Sass 2.0.0. I attempted to ...

There was an issue when trying to process the Javascript data structure with JSON.parse

Currently, I have the following data stored in a JavaScript variable: "{'Headings': [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}}, {'na ...

Tips for sending the setState function to a different function and utilizing it to identify values in a material-ui select and manage the "value is undefined" issue

I am currently utilizing a Material UI select component that is populated with data from an array containing values and options. Within this array, there exists a nested object property named "setFilter". The setFilter property holds the value of setState ...

I continue to encounter the error "Unexpected token b in JSON at position 0" when attempting to parse JSON data

Having some trouble with my code that generates an HTML page. The signup function allows users to register and create a password, while the checkpassword function is supposed to verify if the correct password is entered for the given username. I seem to be ...

What is the best way to create a universal variable that can be accessed across all routes in an Express/

Exploring the world of nodejs and express, I have turned to the Parse API for my backend database needs. At the moment, I have an ajax post triggered on page load to one of my routers /getuser, which retrieves the current user if they are logged in. I am ...

Tips on hovering over information retrieved from JSON data

Within my code, I am extracting information from a JSON file and placing it inside a div: document.getElementById('display_area').innerHTML += "<p>" + jsonData[obj]["name"] + "</p>"; I would like the abi ...

Monitoring a specific property within an array of objects with AngularJS

I am facing an issue with the data in my controller $scope.data = { home: { baseValue: "1", name: "home" }, contact: { baseValue: "2", name: "contract" } // numerous ...

Sort the elements within the *ngFor loop according to the category upon clicking the button in Angular

Currently, I have a collection of items that I am iterating through using *ngFor. Above this list, there are category buttons available as shown in the HTML snippet below. My goal is to enable filtering of the list based on the category of the button click ...

The trio of Javascript, Ajax, and FormData are

I'm struggling with sending form values to a PHP file. Here's the code I have: <form role="form" id="upload_form" method="post" enctype="multipart/form-data"> <div class="form-group"> <label for="formlabel">Title< ...

Leveraging the power of NextJS: Context API for seamless storage and transmission of

I'm currently working on a project with NextJS, aiming to create a shopping cart functionality using the useContext hook. My approach was fairly straightforward - I created a ShoppingCartContext, added an addToCart function to handle pushing data to t ...

Using AngularJS to Retrieve a Specific DOM Element Using its Unique Identifier

Example Please take a look at this Plunkr example. Requirement I am looking for a way to retrieve an element by its id. The provided code should be capable of applying a CSS class to any existing DOM element within the current view. This functionality ...

Struggling with making changes to a instantiated "this" object within a pseudo javascript class

If you scroll down to the bottom of this post, you'll find a workaround or possible solution. I've been grappling with understanding how pseudo classes work together to achieve the task I'm attempting (explained in the code below). It might ...

Can we set a specific length for an array passed in as a prop?

Can we use Typescript to specify the exact length of an array coming from props? Consider the following array of objects: const sampleArray = [ { key: '1', label: 'Label 1', value: 9 }, { key: '2', label: 'Label 2&ap ...

VueJS Array Index causing unexpected output

I have been developing a unique poetry application that pulls in poetry using an API call. To fetch the data, I am utilizing the axios library and using v-for to render the data. The index from v-for is used to load the image for each respective poem. My ...

"Create a React button component that, when clicked, navig

I'm currently developing a web application using React and bootstrap. I'm facing difficulties in redirecting the page to another one when applying onClick to buttons. After adding a href, I'm unable to navigate to another page. Do you think ...