Next.js自定义Google Auth域名后登录重定向出现404问题求助
解决Next.js中Google登录重定向404的问题
1. 先确认Firebase Auth的基础配置
- 打开Firebase控制台,进入Auth > 登录方法 > Google,检查授权重定向URI里是否包含
https://mydomain.com/__/auth/handler,没有的话添加上。 - 再次确认项目配置中的
AuthDomain已经设置为你的自定义域名(不是默认的xxx.firebaseapp.com)。
2. 给/__/auth/handler路径配置处理逻辑
根据你使用的Next.js路由方案,选择对应的配置方式:
如果你用App Router(Next.js 13+)
在项目的app/__/auth/目录下新建route.js(或route.ts)文件,写入以下代码:
import { handleAuth } from '@firebase/auth'; import { auth } from '@/lib/firebase'; // 替换成你项目中Firebase Auth实例的导入路径 export const GET = handleAuth(auth);
这个文件会让Next.js把该路径的GET请求交给Firebase Auth的处理函数,不再返回404。
如果你用Pages Router
在项目的pages/__/auth/目录下新建handler.js(或handler.ts)文件,写入以下代码:
import { handleAuth } from '@firebase/auth'; import { auth } from '../../lib/firebase'; // 替换成你项目中Firebase Auth实例的导入路径 export default handleAuth(auth);
3. 用重写规则代理请求(可选替代方案)
如果不想自己写处理逻辑,可以直接在next.config.js中添加重写规则,把/__/auth/开头的请求代理到Firebase Auth的官方端点:
/** @type {import('next').NextConfig} */ const nextConfig = { async rewrites() { return [ { source: '/__/auth/:path*', destination: 'https://你的AuthDomain/__/auth/:path*', // 替换成你的自定义AuthDomain }, ]; }, }; module.exports = nextConfig;
这样Next.js会自动把该路径的请求转发到Firebase的处理服务,无需额外创建路由文件。
4. 禁用该路径的缓存
为了避免浏览器或CDN缓存这个授权路径导致异常,在next.config.js中添加headers配置:
const nextConfig = { async headers() { return [ { source: '/__/auth/:path*', headers: [ { key: 'Cache-Control', value: 'no-store, max-age=0', }, ], }, ]; }, };
确保每次授权请求都是实时处理的。
内容的提问来源于stack exchange,提问作者Taio
相关产品推荐
相关产品推荐

