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

Is there a way to display the output of jQuery in an input box rather than a span?

I need to display the result of this function in an input box instead of a span tag because I plan to utilize the result in the following form. function checkChange(){ $.ajax({ url: "ordercalculate.php", data: $('form').seria ...

The .each method is failing to iterate over the next object

Currently, I have been working with JSON data retrieved from the web. After successfully receiving the data, I proceed to create a JavaScript object to work with it. However, there seems to be an issue with retrieving the values of fname and lname from th ...

Using Storybook with Amplify in a Next.js application runtime

I am attempting to run Storybook from Amplify in a Next.js project. Initially, the framework was set as Next.js SSR, but I changed it to React while keeping the app platform as Web Compute. In the amplify.yaml file, I made the following updates: version: ...

Error encountered while attempting to load configuration "next/babel" in order to extend from eslintrc.json

During my attempt to create a Next.Js app, I encountered an error after successfully building it. The error only appears when deploying the app on Vercel. Error - ESLint: Failed to load config "next/babel" to extend from. Referenced from: /vercel/path0/.es ...

Once the data is retrieved and the old image is deleted, attempting to upload the new image still results in the old image being displayed in the Next.js application with React Query

async function fetchTour() { const response = await api.get(`/tour/${router.query.slug}`); return response.data; } const { data: tourData, isLoading, isFetching, isTourError: isError, } = useQuery(['fetchTour', router.que ...

Having trouble adding items to an array within a Javascript promise

I am facing an issue with the exported function in a Nextjs app, which acts as an API page. The problem arises when the 'domainnames' array returns nothing in the 200 response. Interestingly, if I exclude the 'GetDomainStatus()' funct ...

Top tips for handling HTML data in JSON format

I'm looking to fetch HTML content via JSON and I'm wondering if my current method is the most efficient... Here's a sample of what I'm doing: jsonRequest = [ { "id": "123", "template": '<div class=\"container\"&g ...

The function validateLogin is not defined within the code, resulting in a javascript exception being

Hey there, I'm encountering an undefined function error and I believe my code is correct. Can someone please offer assistance in this situation? Additionally, could you recommend a good tutorial for fetching data through a webservice using the Ajax me ...

Next.js Version 13 - Unable to find solution for 'supports-color' conflict

Currently in the midst of developing a Next.js 13 app (with TypeScript) and utilizing the Sendgrid npm package. An ongoing issue keeps popping up: Module not found: Can't resolve 'supports-color' in '.../node_modules/debug/src' ...

Issue encountered when utilizing the childNodes.length attribute in JavaScript with elem

I am struggling to accurately find the count of child nodes in my treeview after implementing drag and drop functionality. Whenever I try to determine the number of child nodes, I keep getting a static value of 4 regardless of the actual number of children ...

Tips for refreshing a table component after receiving a notification from a WebSocket in React JS

Currently, I am utilizing React table to load a page that shows a table with data fetched from an API. Additionally, I am listening on a web socket and whenever there is new data sent over the web socket, a console message is printed. My goal now is to a ...

Having trouble with the GitHub publish action as it is unable to locate the package.json file in the root directory, even though it exists. Struggling to publish my node package using this

I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...

The express response fails to include the HTML attribute value when adding to the href attribute of an

When using my Nodejs script to send an express response, I encounter a problem. Even though I set the href values of anchor tags in the HTML response, they are not visible on the client side. However, I can see them in the innerHTML of the tag. The issue ...

Conditions are in an angular type provider with AOT

I am facing an issue with my Angular project that is compiled using AOT. I am trying to dynamically register a ClassProvider based on certain configurations. The simplified code snippet I am currently using is below: const isMock = Math.random() > 0.5; ...

Tips for optimizing iframe loading times using the onload event

I am facing an issue with the timing of iframe loading while using a list of URLs as sources. I have created a child iframe and appended it to the DOM, then run the onload function for further processing. However, the time recorded for each iframe seems in ...

Displaying a progress bar while fetching data in Vue: A step-by-step guide

I am working on developing a progress bar using vue js and bootstrap for my desktop application. Within the template, I have the code that will generate the necessary markup: <div class="container-fluid p-0 vh-100" v-if="isLoading&quo ...

React Redux causing React Router to display empty pages

In my App.js, the following code is present: const Index = asyncRoute(() => import('~/pages/index')) const Register = asyncRoute(() => import('~/pages/register')) const AddDesign = asyncRoute(() => import('~/pages/add-des ...

Having difficulty initializing jQuery DataTables upon button click with an Ajax request

I have a piece of HTML code that represents a partial view: <table id="table_id" class="table table-inverse"> <thead class="thead-inverse"> <tr> <th>Select</th> ...

The React-Toastify module is missing

Having issues with react toast plugin displaying an error. Prior to attempting to use the toast feature, I executed this command: npm install --save react-toastify The following error is being shown in Google Chrome Console: ERROR in ./src/Pages/Login ...

What is the best way to interweave my objects within this tree using recursion?

I am working on creating a new function called customAdd() that will build a nested tree structure like the one shown below: let obj = [] let obj1 = { key: "detail1Tests", id: "94d3d1a2c3d8c4e1d77011a7162a23576e7d8a30d6beeabfadcee5df0876bb0e" } ...