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

Checking Whether a Value Entered in an Input Field Exists in an Array Using jQuery

Can someone help me with checking if a specific value is in my array? I want to achieve something like that, any suggestions on how to do it? if(jQuery.inArray($('#ValueInputTitle').val, variableValueInput) !== -1) { console.log("is in arr ...

Enhance TinyMCE functionality to permit text as a primary element within <table> or <tr> tags

I've been struggling for the past three hours, trying out different solutions and searching like crazy on Google. Unfortunately, I have not been able to find a resolution to this particular issue. Issue: TinyMCE is not allowing me to insert text dire ...

Is it possible to automatically access the most recent Beta build through package.json and npm?

We are currently working on a project that has a specific dependency requirement for the latest beta build from an npm library. However, there are also -dev builds within the library. For instance, in the "x-library" there might be versions like: "1.2.3- ...

What is the method to escape from a for loop in Protractor?

Check out my code snippet: formElements[0].findElements(by.repeater(repeater)).then(function(items){ console.log(i, '>>>>>>>>>.No of items in the list --- '+items.length); (function(items){ ...

JavaScript Class Reference Error

Questioning the mysterious reference error in the JS class from MDN page. The structure of the Bad class's constructor leaves me baffled – is it because the empty constructor calls super() as a default? class Base {} class Good extends Base {} cla ...

Angular 6 canvas resizing causing inaccurate data to be retrieved by click listener

The canvas on my webpage contains clickable elements that were added using a for loop. I implemented a resizing event that redraws the canvas after the user window has been resized. Everything works perfectly fine when the window is loaded for the first ti ...

Tips on generating an HTML element using JavaScript and storing it in a MySQL database

I need help with saving a created element to the database so that it remains on the page even after refreshing. Any assistance would be greatly appreciated. Thank you. document.getElementById("insert").onclick = function(){ if(document.getElementById( ...

VueJS refreshes components while preserving previous data

As a newcomer to VueJs, I am currently working with a Practice component that includes an ExerciseMC component. The parent component retrieves a question object (with a text property) from the backend through a request and passes it as a prop to the Exerci ...

Angular displaying undefined for service

I have created a service for uploading images to a server, and I am encountering an issue when calling this service from my controller. The error message indicates that the function 'uploadFileToUrl' is undefined. Below is the code for my servic ...

Can you provide tips on how to center the title on the page?

Currently, I am working on codepen.io and have been tasked with creating a paragraph that includes a title. However, my dilemma lies in the fact that I need this title to be center-aligned without directly altering the "x" value. Unfortunately, CSS is not ...

Updating pages dynamically using AJAX

There's a glitch I can't seem to shake off. I've successfully implemented AJAX for page loading, but an issue persists. When I navigate to another page after the initial load, the new page contains duplicate tags like <head> and <f ...

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Unsuccessful CORS on whateverorigin.org with YQL

Despite trying all three methods, I keep getting an error regarding cross domain access denied. Previously, I had successfully used YQL in different parts of my applications, but now it seems to have stopped working as well. JSFIDDLE <script> $(fun ...

Unable to retrieve an image from various sources

My setup includes an Express server with a designated folder for images. app.use(express.static("files")); When attempting to access an image from the "files" folder at localhost:3000/test, everything functions properly. However, when trying to ...

Incorporate the Yammer share button into a Next.js application

Implementing the Yammer share button in next.js may seem straightforward at first glance. After reviewing the documentation provided by Yammer, it appeared as though I just needed to include the source in the Head Component and then call it using the <s ...

Executing a component's function from a JavaScript file

Is it possible in React to call a function or method of a component from a separate JS file in order to modify the component's state? Here are three example files: First, App.js import React,{Component} from 'react'; import Login from &ap ...

What steps can I take to rearrange my return statement within an asynchronous function?

Imagine having a function that fetches data from a database. findById(id) { return Model.findById(id) } The goal is to rearrange the output from the user data in this format: { name: "Tom", age: 57 } To something like this: { message: ...

The method for retrieving values and $id from a $firebaseArray using angularJS

Hey there, I'm fairly new to working with Firebase and I seem to be stuck on a problem that I can't find a solution for despite looking in many different places. Here is the structure of my Firebase database: I am trying to retrieve data from a s ...

Trouble arises with MySQL query in PHP/jQuery setup

I am currently in the process of developing a user panel where users can change their first and last names. Everything seems to be working fine with the $ajax form handling, as I can use console.log(data) and see {fname: "Damian", lname: "Doman", id: "20" ...