Auth0 UserProvider 与 NextJS 应用程序路由器

问题描述 投票:0回答:3

我正在使用 app/ 目录将公司的整个 React 应用程序重写到 NextJS 13.4.8 上。我们使用 Auth0 作为身份验证提供程序(没有计划使用 NextAuth),并且来自带有应用程序路由器的

nextjs-auth
的文档(目前处于测试版,https://github.com/auth0/nextjs-auth0/tree/beta# app-router)我认为它应该可以工作......不知何故。到目前为止,它是一个普通的 NextJS 应用程序,因此它是一个开放的沙箱。

问题是应用程序本身可以编译,但是当转到浏览器时出现以下错误:

- error TypeError: Cannot read properties of undefined (reading 'auth0')
    at eval (webpack-internal:///(sc_server)/./node_modules/.pnpm/@[email protected][email protected]/node_modules/@auth0/nextjs-auth0/dist/handlers/auth.js:49:47)
    at step (webpack-internal:///(sc_server)/./node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.mjs:260:23)
    at Object.eval [as next] (webpack-internal:///(sc_server)/./node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.mjs:201:20)
    at eval (webpack-internal:///(sc_server)/./node_modules/.pnpm/[email protected]/node_modules/tslib/tslib.es6.mjs:179:71)
    at new Promise (<anonymous>)

我已经完成了以下操作(使用他们的 gh 上的文档):

  • 已创建
    app/api/auth/[auth0]/route.ts
// app/api/auth/[auth0]/route.ts
import { handleAuth } from '@auth0/nextjs-auth0';

export const GET = handleAuth();
  • 用来自
    RootLayout
    UserProvider
     包裹 
    @auth0/nextjs-auth0/client
// src/app/layout.tsx
import './globals.css';
import { UserProvider } from '@auth0/nextjs-auth0/client';

export const metadata = {
  ...
};

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <UserProvider>
      <html lang='en'>
        <body>{children}</body>
      </html>
    </UserProvider>
  );
}
  • login
    页面上我正在返回
    <a href='/api/auth/login'
    -
    'use client'
    在那里
// src/app/login/page.tsx
'use client'
import { useUser } from '@auth0/nextjs-auth0/client';
...

export default function Login() {
  ...
  const { user, error, isLoading } = useUser();
  ...
  return (
    <a href='/api/auth/login'>
      <Button size='lg'>
         Login
      </Button>
    </a>
  )
}
  • .env.local
    内部有:
    AUTH0_SECRET
    AUTH0_BASE_URL
    AUTH0_ISSUER_BASE_URL
    AUTH0_CLIENT_ID
    AUTH0_CLIENT_SECRET
    ,取自Auth0仪表板 - 此数据与React应用程序
  • 中的数据相同

我的解决方案有问题吗,或者此集成中存在错误,或者您在此处看到的可能还有其他问题?

请寻求任何帮助🚀

next.js auth0 next-auth
3个回答
0
投票

我遇到了同样的问题,我通过将 auth0 @auth0/nextjs-auth0 升级到 3.0.0-beta.3 解决了它

试试这个

npm i @auth0/[email protected]

https://www.npmjs.com/package/@auth0/nextjs-auth0?activeTab=versions


0
投票

制定路线:

应用程序/api/auth/route.ts

不是

应用程序/api/auth/[auth0]/route.ts


0
投票

老问题,但我很确定你的问题是/是你正在使用

import { UserProvider } from '@auth0/nextjs-auth0/client';
文件中的
src/app/layout.tsx
(例如客户端包),但事实并非如此,或者至少从提供的代码来看没有似乎被标记为
use client
,因此位于设置的服务器端。

您可以通过在客户端组件中使用

UserProvider
来修复它(可能只是您的
layout.tsx
的子组件,但标记为
use client
)。

© www.soinside.com 2019 - 2024. All rights reserved.