NextJS13 + Auth0 - 根据某些条件重定向用户

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

我正在使用 NextJS13 + Auth0 构建一个新应用程序。 NextJs 版本是

13.4.19
,而 auth0 lib 版本是
3.1.0
。我正在使用服务器组件。文件是
\app\api\auth\[auth0]\route.ts

我有一个自定义回调处理程序

const afterCallback = async (req: NextRequest, session: Session, state: { [key: string]: any }) => {
    if (session.user.email_verified) {
        console.log('email verified..continuing')
        return session;
    } else {
      // redirect('http://localhost:3000/verify-email', RedirectType.replace);     
      // return NextResponse.redirect(new URL('http://localhost:3000/verify-email'))
       headers.set('location', '/verify-email');
    }

    console.log('printing after redirect')    
    return session;
};

我的 authHandlers

export const GET = handleAuth({
    callback: async (req: any, res: any) => {
        try {
            console.log('callback method called')
           return await handleCallback(req, res, {
                afterCallback,
               // redirectUri: 'http://localhost:3000/dashboard'
            });
        } catch (error) {
            console.error(error);
        }
    },

  login: async (req: NextApiRequest, res: NextApiResponse) => {
        console.log('login method called')
        return await handleLogin(req, res, {
            // authorizationParams: {
            //     redirect_uri: 'http://localhost:3000/api/auth/callback',
            //   },
            returnTo: `/dashboard`,
        });
    },

当用户的电子邮件未验证时,我不确定如何将用户重定向到

/verify-email
页面。

我尝试了不同的选择,但没有运气。根据文档,使用

redirect
会引发错误。- https://nextjs.org/docs/app/api-reference/functions/redirect 文档中还有另一个使用
headers.set('location', '/verify-email');
的示例 然而,这也不起作用,因为标头是只读的。我收到以下错误
CAUSE: next_headers__WEBPACK_IMPORTED_MODULE_1__.headers.set is not a function

有谁知道如果电子邮件未经验证,我如何将用户推送到

/verify-email
页面。 TIA

redirect next.js auth0 next.js13
1个回答
0
投票

请参阅此处的文档:https://github.com/auth0/nextjs-auth0/blob/26b54f3/src/handlers/callback.ts#L74C4-L74C4

 * @example Redirect successful login based on claim
 *
 * ```js
 * // pages/api/auth/[auth0].js
 * import { handleAuth, handleCallback } from '@auth0/nextjs-auth0';
 *
 * const afterCallback = (req, res, session, state) => {
 *   if (!session.user.isAdmin) {
 *     res.setHeader('Location', '/admin');
 *   }
 *   return session;
 * };
 *
 * export default handleAuth({
 *   async callback(req, res) {
 *     try {
 *       await handleCallback(req, res, { afterCallback });
 *     } catch (error) {
 *       res.status(error.status || 500).end(error.message);
 *     }
 *   }
 * });
 * ```
© www.soinside.com 2019 - 2024. All rights reserved.