Adding auth0 authentication to a Next.js 13 application: A step-by-step guide

Currently, I am using a nextjs 12 application and set up auth0 as my authentication provider by following the guidelines provided here: https://auth0.com/docs/quickstart/webapp/nextjs/interactive. However, I am now looking to upgrade my application to nextjs 13, but I have not been able to find any documentation on this specific upgrade process.

In nextjs 12, the UserProvider wraps the entire app in _app.tsx as shown below:

import "../styles/globals.css";
import type { AppProps } from "next/app";
import { UserProvider } from "@auth0/nextjs-auth0/client";

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <UserProvider>
      <Component {...pageProps} />
    </UserProvider>
  );
}

export default MyApp;

With the changes introduced in nextjs 13, I needed to make adjustments within the main page.tsx file as follows:

import { UserProvider } from "@auth0/nextjs-auth0/client";
import "../styles/globals.css";

export default function RootLayout({
  // Layouts must accept a children prop.
  // This will be populated with nested layouts or pages
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <UserProvider>
        <body>{children}</body>
      </UserProvider>
    </html>
  );
}

However, when attempting to access 'http://localhost:3000/api/auth/login', I encounter the following error related to CORS policy restrictions:

Access to fetch at 'https://domain.eu.auth0.com/authorize?client_id=test_number&scope....' (redirected from 'http://localhost:3000/api/auth/login') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I made sure to add http://localhost:3000 and as Allowed Origins CQRS and Allowed Web Origins in the Auth0 dashboard settings.

If anyone has experience integrating auth0 into a nextjs 13 application or any insights into resolving the CORS issue mentioned above, I would greatly appreciate it. Thank you!

Answer №1

As per the ongoing issue on Github regarding this topic, there are plans to add support for the app directory once it is deemed stable.

In the meantime, you can implement a workaround like so:

import { cookies } from 'next/headers';


const getUser = async () => {
  const res = await fetch(`${process.env.AUTH0_BASE_URL}/api/auth/me`, {
    headers: {
      cookie: `appSession=${cookies().get('appSession')?.value}`
      // cookie: cookies().getAll().map(c => `${c.name}=${c.value}`).join(';') -- all cookies
    }
  })
  return await res.json()
}

const Home = async () => {
  const user = await getUser();

  return (
    <p>
      {JSON.stringify(user)}
      <br/>
      <a href="/api/auth/login">LOG IN</a>
    </p>
  )
};

export default Home

NextJS 13: support for server-side components in nextjs-auth0

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

Why doesn't Material-UI seem to understand the theme.spacing function?

Issue with Material-UI's theme.spacing function I've encountered a problem while using Material-UI's theme.spacing function in a React application. It seems that the spacing function is not being recognized. The Javascript error message st ...

Modify the size of images while shuffling using Javascript

Hey there! I've got some bootstrap thumbnails set up and I'm using a script to shuffle the images inside the thumbnails or a element within the li. It's working fine, but some of the images are coming out larger or smaller than others. I&apo ...

Ways to fix the error "Response must contain an array at." when creating a dropdown menu

I encountered an error while trying to create a dropdown menu. I referred to the documentation available at The response must include an array at " . ". Although I came across some links with potential solutions, none of them seemed to work for me: https ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

extract data from a JSON-formatted object

While developing my asp.Net application using MVC 3, I encountered a situation in which I was working with a jQuery control. I received a JSON response that looked like this: { "text":"Books", "state":"open", "attributes":{ ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Preventing Users from Accessing a PHP Page: Best Practices

I'm currently focusing on a problem that involves restricting a user from opening a PHP page. The following is my JavaScript code: <script> $('input[id=f1email1]').on('blur', function(){ var k = $('inp ...

NextAuth - Instead of redirecting to the callback URL, it remains on the sign-in page

In my current projects involving Next.js and NextAuth, I have a custom sign-in page with the following configurations: Package.json "next": "^12.0.8" "next-auth": "^4.2.1" [..nextauth].js pages:{ signIn:'/au ...

Generate Sub Menu for Navigation Bar based on Main Menu Selection

I'm currently working on dynamically setting menu items and sub menu items using React Props. My code successfully iterates through the main list items navItems.label and displays them. However, I'm facing an issue with displaying the sub menu i ...

Creating a CSS triangle that smoothly transitions between two different colors

Is it possible to create a triangle in CSS that smoothly transitions between two colors without relying on a hover state? .arrow-down { width: 0; height: 0; border-left: 20px solid transparent; border-right: 20px solid transparent; b ...

What steps should I take to ensure that my Next.js app's production build stays synchronized in real-time with Firestore

Exploring firebase and nextjs, as well as static site generation, is a new venture for me. My image album website is currently hosted on vercel, connected to both firebase storage and firestore database. During development, everything functions smoothly. ...

"Looking for a way to automatically close the <li> tag in Vuejs when clicked outside

clickOutside: 0, methods: { outside: function(e) { this.clickOutside += 1 // eslint-disable-next-line console.log('clicked outside!') }, directives: { 'click-outside': { ...

What steps do I need to take in order to implement a functional pagination menu in Vue?

I downloaded and installed laravel-vue-pagination with the following command: npm install laravel-vue-pagination After that, I globally registered it in my app.js file: Vue.component('pagination', require('laravel-vue-pagination')); F ...

How can I efficiently update child states within a parent class using ReactJS?

Exploring the parent component class Root extends React.Component { constructor(props) { super(props); this.state = { word: Words, }; } c ...

Using jQuery idle timeout to abort jQuery AJAX calls in Laravel 5.2

Currently, I have implemented the jQuery Idle Timeout plugin in my Laravel 5.2 system. Everything works perfectly on my local setup using MAMP Pro, but upon uploading it to the development server, I encountered an "Aborted" error in the AJAX get request: ...

Calculate the total value of each individual subject from the checkbox's data-id, presented in a string format and separated by commas

<div> <input type="checkbox" id="Q_1_ck1" value="R" data-id="Environmental Science, Physical Education, Agriculture, Yoga, "> <label class="custom-control-label" for="Q_1_ck1"> ...

What is the best way to store a picture sent from my NextJS client to my NodeJS server?

Last week, I attempted to upload an image to my NodeJS server and then save it to an S3 bucket, but I encountered a problem with the initial step as my server was not receiving the image. To handle the saving process in the 'public/' folder, I am ...

Incorrect pathing in express.js

I've encountered an issue with my filter while attempting to redirect packages using two express.js routes: app.get('/billdetails/:year/:month/:phoneId', function (req, res, next) { var db = req.db; var year = req.params.year; v ...

Next.js encountered an error: React cannot render objects as valid children, as it found a promise object instead

Currently implementing dynamic routing in Nextjs and aiming to obtain the client's IP address before initiating Server Side Rendering. This is crucial for adding custom headers required for Social Media sharing. Below is the code snippet: function m ...

What is the best way to adjust the size of carousel images within a box element?

How can I ensure that carousel pictures are displayed clearly within the box without overflowing? The code I tried resulted in the pictures overflowing from the box and not being visible clearly. How can I resolve this issue? .container { width: 1490px; ...