During operation, invoking the next-auth function Signout() in production will direct the user to "localhost:3000" regardless of whether a callbackUrl is provided

After successfully deploying my Next.js app to AWS Amplify and setting up my environment variables correctly (including APP_URL and NEXTAUTH_URL, which are the same), I encountered an issue when attempting to sign out using credentials from MongoDB Atlas. Instead of being redirected appropriately, I found myself redirected to localhost:3000.

Upon inspecting the Network tab of DevTools, I noticed a call named 'signout' with a 200 response and a Payload that seemed fine:

csrfToken: 20dc1de55c4e40c7c0ac8d3ce675bff4522ba665d79e04c9da00f6365a23c30c
callbackUrl:
json: true

However, the Request Headers of this 'signout' call indicated an issue with the 'cookies' entry:

cookie: (...) next-auth.callback-url=http%3A%2F%2Flocalhost%3A3000 (...)

Following the 'signout' call, I observed another call named 'localhost' being repeated intermittently while the page was open, using headers that pointed to a localhost URL:

General
Request URL: http://localhost:3000/
Referrer Policy: strict-origin-when-cross-origin
Request Headers
Provisional headers are shown Learn more
sec-ch-ua: "Not_A Brand";v="99", "Google Chrome";v="109", "Chromium";v="109"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36

Despite my environment variables being correctly set in AWS Amplify, with NEXT_PUBLIC_APP_URL and NEXT_PUBLIC_NEXTAUTH_URL both pointing to the same URL, the issue persisted.

Even after simplifying my Signout() function and verifying the environment variables by logging them, the issue remained unresolved. I attempted different approaches such as changing the callbackUrl and calling Signout() without any parameters, but to no avail.

I thoroughly checked my codebase for any references to localhost:3000, including the env.local file that was not pushed to Github, but found nothing. I also tried suggested solutions from GitHub threads, but none of them addressed the problem.

Despite creating a new AWS Amplify app to eliminate cached files, the issue of being redirected to localhost:3000 persisted in production. This redirection was puzzling considering the absence of any localhost references in my code.

For further examination, my repository can be found here (Master branch is being deployed): https://github.com/joaotextor/trading-center

Live preview and credentials are available in the Github Repository to prevent this question from being flagged as spam. Your help is appreciated!

Answer №1

Upon careful investigation of the code, I reached a conclusion that the next-auth redirect, callbackUrl, and cookie setting were experiencing bugs. However, I was able to find a workaround to address this issue.

Before I delve into the solution that I applied, let me first outline the bug that I encountered:

The bug became apparent to me when I utilized the redirect() callback within the [...nextauth].js file.

callbacks: {
  async redirect({ url, baseURl }) {
    console.log(`URL: ${url}`)
    console.log(`BASEURL: ${baseUrl}`)
  }
}

The baseUrl value was returning as http://localhost:3000

Additionally, I experimented with setting useSecureCookies to "true" and programmatically setting the callback-url cookie in the nextauth options:

  useSecureCookies: true,
  
  cookies: {
    callbackUrl: {
      name: '__Secure-next-auth.callback-url',
      options: {
        sameSite: 'lax',
        path: 'https://tradingcenter.joaotextor.com',
        secure: true
      }
    }
  }

To my surprise, despite configuring the setup in this manner, the cookie value persisted as 'http://localhost:3000'!

This led me to realize that if the redirect URL was localhost, I should have been redirected to it when signing in, not just when signing out.

Recalling a past issue with the redirect in the SignIn() function during system development, I remembered implementing a workaround using the useRouter from next/router.

Subsequently, I applied a similar fix to the SignOut function by setting the redirect prop to 'false' and utilizing router.push() to navigate to the desired path:

<MenuItem onClick={() => {
  signOut({redirect: false})
  router.push(process.env.NEXT_PUBLIC_NEXTAUTH_URL)
}}>Logout</MenuItem>

Following these adjustments, everything functioned as intended.

Answer №2

Dealing with a similar error, I found that my issue was due to the incorrect environment variable being set to

NEXTAUTH_URL=http://localhost:3000

Once I corrected it to

NEXTAUTH_URL=https://example.com

the problem was resolved for me.

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

Within Vuex, the object store.state.activities contains a specific key labeled "list" which initially holds an array of three items. However, when attempting to access store.state.activities.list directly, an empty array

My project is utilizing Vue. The store.state.activities object contains 2 keys, including an array named list with 3 elements. However, despite attempting to access it using store.state.activities.list, I am getting an empty array. I have experimented w ...

Why isn't the program recording user input in the console when the form is submitted?

Can someone please advise me on how to get the program to print the user's input values to the console when they click the "Sign up now" button? ...

Show the button's value on the text box using JavaScript

When using bootstrap, I encountered an issue where the value of a button would display in a textbox upon clicking it, but then quickly disappear. This unexpected behavior left the textbox empty prematurely. <input type="submit" value="5000t "class="btn ...

Create a WebGL object remotely on the server

Exploring potential project ideas, I was curious to see if it's feasible to produce a WebGL scene or object on the server side and then have it rendered on the client. The motivation behind this is that generating a scene typically involves utilizing ...

Struggling to Make Div Refresh with jQuery/JS in my Rails Application

I'm currently facing an issue in my Rails app where I am unable to refresh a specific Div element. The Div in question is located in bedsheet_lines_index.html.erb <div id="end_time_partial" class="end_time_partial"> <%= render :partial ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

Adding External JS Files to a Node.js Project

I recently discovered how to incorporate a JS file into Node JS. However, I am facing an issue with two JS files in particular - hashing.js and encoding.js. Within encoding.js, I have the following code: exports = exports || {}; exports.encoding = encodi ...

Cannot retrieve Global variables when using chrome.tabs.executescript in Chrome 55

After recently updating Chrome to version 55.0.2883.75, I encountered an issue with my self-developed Chrome Plugin used for parsing HTML files. In the plugin, I utilize chrome.tabs.executescript to retrieve data from a background HTML page. Previously, I ...

Encountering an issue where the getServerSession function consistently returns null within API route handlers in Next.js 13.5.2 when utilizing NextAuth for

`I am currently experimenting with a To-Do application to enhance my skills in Next.js and Next-Auth. My objective is to utilize Next-Auth as the OAuth Provider and include a 'createdBy' property for each to-do item linked to the respective user ...

Exploring the implementation of --history-api-fallback in webpack

let path = require('path') module.exports = { entry:path.resolve('public/src/index.js'), output: { path:__dirname + "/public", filename: "bundle.js" }, module: { loaders: [{ exclude: / ...

Drop down calendar in Javascript

I am in the process of developing a virtual JavaScript calendar dropdown feature. I aim to have the correct number of days displayed upon selecting a month, but currently, no days appear when I make a selection. Can someone please assist me with this iss ...

Utilize Javascript to establish a fresh attribute by analyzing other attributes contained in an array within the object

Currently, I am working on a data structure that looks like this: masterObject: { Steps: [ { step: { required: false, }, step: { required: false, }, step: { required: false, }, }, ] } ...

Guide to switching content within a DIV when the up and down buttons are pressed using JavaScript and jQuery

I have a functional code with a timeline where each event is connected to the other. There are buttons to delete and copy data, but I want to implement functionality for swapping elements when the up or down button is clicked. I have provided a sample code ...

Tips for accessing $parent of ng-repeat from ng-include

In my code, I have a nested ng-repeat structure with an ng-include inside the inner ng-repeat. I am trying to access the outer ng-repeat using $parent within the ng-include. Here is an example of what I am working on: index.html <div ng-repeat="popula ...

Tips for sending an email to an address from a user input field in React.js/Express.js

I am currently developing an email application that allows users to send emails to any recipient of their choice. The challenge I'm facing is that I need a way to send emails to user-specified email addresses without requiring passwords or user.id det ...

Server-side props become inaccessible on the client side due to middleware usage

I'm attempting to implement a redirect on each page based on a specific condition using Next.js middleware. Strange enough, when the matcher in middleware.ts matches a page, all props retrieved from getServerSideProps for that page end up being undef ...

Can you clarify the dissimilarity between `knex().select("id").from("users")` and `knex("users").select("id")` in Knex?

I have successfully connected knex with mysql and am working on a login form linked to a mysql database. Currently, I am performing a login check and I'm curious if there is any distinction between the following two queries: knex().select("id").from( ...

What is the best way to conceal two Bootstrap divs that should not both be visible at the same time?

I am working with two different types of charts: an Emotion chart and a Polarity chart. To control the visibility of these charts, I have implemented two buttons, one for each chart. The functionality is such that when the first button is clicked, only the ...

Switching the theme color from drab grey to vibrant blue

How can I change the default placeholder color in md-input-container from grey to Material Blue? I have followed the instructions in the documentation and created my own theme, but none of the code snippets seems to work. What am I doing wrong? mainApp. ...

Viewing a Google Charts graph upon the loading of a web page

Utilizing the Google Charts library, I have incorporated a graphic on my web page that is dynamically added using AJAX into a <div> element. To display the graph when the page loads, I have written the following code: <script type="text/ ...