Next.js App experiences a 404 Error when attempting to access the Auth0 Endpoint "api/auth/me"

Following a tutorial, I integrated my Next.js App with Auth0 successfully. However, after logging in and out, I encountered an issue where the user object is not returned when trying to display user information on the page post-login. Both the Profile.js page rendering and the env.local file with the app's secret keys seem to be in order.

Upon further investigation, I found an error in the browser console stating:

Failed to Load Resource ... 404 Not Found: http://localhost:3000/api/auth/me
.

This error suggests a discrepancy in the mapping between my Next.js app and Auth0, possibly due to modifying the basepath in next.config.js:

module.exports = {
  basePath: '/my_path',

  webpack: (config) => {
    return config
  },

  env: {
  },

  publicRuntimeConfig: {
    BACKEND_API_URL: process.env.BACKEND_API_URL,
    CONSENT_COOKIE_NAME: 'ConsentCookie'
  },
}

I am looking for a way to include my basepath in the endpoint that returns the user object, resulting in something like:

https://localhost:3000/my_path/api/auth/me

To resolve the issue of the user object not being returned properly, I am open to suggestions and providing more context on specific files in my app.


Edit: After discussing this issue on the Auth0 forums (link), I was directed to this link, which showcases another Next.js Auth0 sample app written in TypeScript. They manipulate the UserContext object and reset the ProfileURL, an action I am interested in. What would be the JavaScript equivalent of this?

Additionally, the same forum response shared another link to a function that creates a custom login URL. This aligns with my goal of creating a custom auth URL to retrieve the User object and resolve the 404 ... /api/auth/me not found error. Given my limited experience with JS, I struggled to replicate the function from the example provided. Can you guide me on how to achieve this?

Answer №1

Emotions of both joy and frustration overwhelm me as I stumble upon a ridiculously simple solution to this problem.

Discovered within the readme.md of the NextJS-Auth0 repository... This small code snippet resolved all my dilemmas after endless hours of searching -

// _app.js
function App({ Component, pageProps }) {
  return (
    <UserProvider loginUrl="/foo/api/auth/login" profileUrl="/foo/api/auth/me">
      <Component {...pageProps} />
    </UserProvider>
  );
}

Time to dry the tears on my desk and move on..

Answer №2

I encountered a similar issue recently with my Next application deployed on Vercel. The problem was that all the api/auth/* routes were not functioning properly in the production environment, while they worked perfectly fine locally.

For authentication, I'm utilizing the Auth0 Universal Login Experience.

// package.json
...
"dependencies": {
    "@auth0/nextjs-auth0": "^1.9.2",
}
...

Prior to this issue, I only had the following function:

// api/auth/[...auth0].ts
import { handleAuth } from "@auth0/nextjs-auth0";

export default handleAuth();

To resolve the problem, I decided to create separate files for each required path in my application. It seemed like Next.js was not generating the dynamic files for [...auth0].ts.

// api/auth/callback.ts
import { handleCallback } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";

const callbackHandler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    await handleCallback(req, res);
  } catch (error) {
    res.status(error.status || 400).end(error.message);
  }
};

export default callbackHandler;

// api/auth/login.ts
import { handleLogin } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";

const loginHandler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    await handleLogin(req, res, {
      authorizationParams: {
        screen_hint: "login",
      },
    });
  } catch (error) {
    res.status(error.status || 400).end(error.message);
  }
};

export default loginHandler;

// api/auth/logout.ts
import { handleLogout } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";

const logoutHandler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    await handleLogout(req, res);
  } catch (error) {
    res.status(error.status || 400).end(error.message);
  }
};

export default logoutHandler;

// api/auth/me.ts
// not api/auth/profile.ts

import { handleProfile } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";

const profileHandler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    await handleProfile(req, res);
  } catch (error) {
    res.status(error.status || 400).end(error.message);
  }
};

export default profileHandler;

// api/auth/signup.ts

import { handleLogin } from "@auth0/nextjs-auth0";
import { NextApiRequest, NextApiResponse } from "next";

const signupHandler = async (req: NextApiRequest, res: NextApiResponse) => {
  try {
    await handleLogin(req, res, {
      authorizationParams: {
        screen_hint: "signup",
      },
    });
  } catch (error) {
    res.status(error.status || 400).end(error.message);
  }
};

export default signupHandler;

Answer №3

For resolving this issue, you can take the following steps:

  1. .env file:
AUTH0_SECRET='****'
AUTH0_BASE_URL='http://localhost:3000/baseURL/'
AUTH0_ISSUER_BASE_URL='***'
AUTH0_CLIENT_ID='***'
AUTH0_CLIENT_SECRET='***'

  1. _app.tsx file:

  <UserProvider profileUrl="/baseURL/api/auth/me">
    <AuthContextProvider>
      <AuthLayout>
        <Component {...pageProps} />
      </AuthLayout>
    </AuthContextProvider>
  </UserProvider>

  1. /api/auth/[auth0].tsx file:
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();
  1. login.tsx file:
<Link href="/api/auth/login">
    Sign In with Auth0
</Link>

Answer №4

If you find yourself arriving here after a late-night Google search:

The issue may arise if you have files with the extensions .ts or .tsx located in the /api directory, but you are anticipating your functions to be in the /pages/api directory. This can lead to path resolution problems in NextJS, resulting in 404 errors.

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

Does moment/moment-timezone have a feature that allows for the conversion of a timezone name into a more easily comprehendible format?

Consider this example project where a timezone name needs to be converted to a more readable format. For instance: input: America/Los_Angeles output: America Los Angeles While "America/Los_Angeles" may seem human-readable, the requirement is to convert ...

The code functions correctly when retrieving information from a file, however, encounters issues when retrieving data

While working on my React application, I encountered a situation where I needed to read the value for translation from a file stored in the public folder. The files were saved at https://i.sstatic.net/oWXCh.png However, due to the dynamic nature of our d ...

Techniques for verifying phone numbers from various countries

The number of digits in a mobile number differs from country to country. I have tried using regular expressions, however, for example, India allows 10 digits, but this does not validate UAE, where the number of digits can range from 7 to 9. ...

Guide on sending a JavaScript function to a Pug file using Node.js and Express

In my recent project, I developed a node app using express along with a pug file. The express app is configured to listen on port 3000 and render the pug file. One of the key functionalities involves fetching information from an external API. My goal is to ...

Troubles encountered during the development of Nextjs/Javascript application

I encountered the following errors while developing my application. I am unsure of the reason behind this issue. I created a fetch request in a separate function and attempted to call this fetch function (which is structured as a custom react hook) within ...

"Struggling with setting the default checked state for single and multiple checkboxes? The ng-init method with checkboxModel.value=true seems to be ineffective – any suggestions

<input type="checkbox" ng-model="isChecked.value" ng-true-value="'yes'" ng-false-value="'no'" ng-click='handleCheckboxChange(isChecked.value, idx);' ng-init="isChecked.value=true" /> ...

The JSON response may be null, yet the data flows seamlessly to the success function in

Currently, I am facing an issue with Ajax. The situation is as follows: I want to check if a user is available by typing their email address. Therefore, I have created a JavaScript function that includes an Ajax script for this purpose. Here is my code: $ ...

"Utilize Javascript to upload a picture and showcase it on your website

<!DOCTYPE html> <html> <head> <title>Unique Webpage!</title> <meta charset=utf-8 />                       <link rel="stylesheet" href="styles/customcss.css" /> <script src="j ...

The integration between React hook form and reactstrap input components is not functioning properly

Having an issue with react-hook-form and reactstrap. The component List.jsx is causing trouble: import { useContext, useEffect } from "react"; import { ListContext, ADD_LIST } from '../providers/ShoppingListProvider'; import { Link } from "react- ...

Issue with the recursive function in javascript for object modification

I have all the text content for my app stored in a .json file for easy translation. I am trying to create a function that will retrieve the relevant text based on the selected language. Although I believe this should be a simple task, I seem to be struggl ...

Using TypeScript to define a constant array as a type

I've hit a roadblock in my typescript project while trying to define a suitable type. Here's the setup: Within my project, I have the following constant: export const PROPERTYOPTIONS = [ { value: "tag", label: "Tag" }, { ...

React encountered an issue: each child element within a list must be assigned a unique "key" prop

I am feeling a bit puzzled as to why I keep getting the error message: child in a list should have a unique "key" prop. In my SearchFilterCategory component, I have made sure to add a key for each list item using a unique id. Can you help me figu ...

ReactJs: How useEffect is invoked before onClick function in NextJS

I am facing an issue with a button in my Next project. Here is the code for the button: <Button minWidth={'140px'} onClick={() => exec(scope)} >Save</Button> When this button is clicked, it triggers the following function: c ...

Utilizing Mirth Connect to insert XML data into a MySQL database using JavaScript

I am completely new to working with Mirth, JavaScript, and MySQL. I have successfully set up a channel in Mirth to read a text file and convert it to XML. Everything is functioning properly so far. I also attempted to send the XML data to a MySQL databas ...

Guide on enabling users to input slide number and URL address to load content using Ajax

Is there a way to customize the number of slides in a slider and choose which content is loaded into each slide using AJAX calls in jQuery? Currently, my slider uses the jQuery .load() method to dynamically load content into each slide when it becomes vis ...

Issues with Internet Explorer's scaling functionality are preventing it from operating correctly

I've utilized d3 to create a map. Its width is dynamically set based on the parent div's (with the id "map") width, and its height is calculated with a ratio of 5/9 in relation to the width. The viewBox attribute has been defined as "0 0 width he ...

What is the best way to extract a specific line from a command using a child process in a Node.js environment?

I am attempting to retrieve the disk space of a virtual machine using a child process in Node.js. Below is the code I have written for this purpose: const { exec } = require('child_process'); function diskSpace(err, result) { exec('df - ...

Utilizing React to dynamically load JSON data and render a component

I am currently facing a challenge in rendering a React component that includes data fetched from a JSON using the fetch() method. Although the API call is successful, I am experiencing difficulties in displaying the retrieved data. Below is the code snip ...

What's the process for setting a value in selectize.js using Angular programmatically?

Currently, I am implementing the AngularJS directive to utilize selectize.js from this source: https://github.com/kbanman/selectize-ng In my scenario, I have two dropdowns and my goal is to dynamically populate one of them called selectizeVat based on the ...

Utilizing a single component for various purposes with diverse tags in react

I am faced with the challenge of creating two almost identical components, Component A: const ClaimedLabel = ():React.Element => ( <div tw=""> <p tw="">Some Text here</p> <div tw=""> <Icon ...