Skip to content

Commit 83c6c52

Browse files
committed
fix(login): SignInButton 走同源 rewrite 避免 hardcode 后端端口
SignInButton 之前 fallback 到 http://localhost:8080,在后端跑 8081 的本地 环境就直接打不通。参考 /analytics、/auth、/api/user-center 的 rewrite pattern, 改用同源 /oauth/render/github,next.config.mjs 补一条 /oauth/:path* → BACKEND_URL。 前端不再关心后端端口,换端口时只改 .env 里 BACKEND_URL 即可。 仍然存在的限制(不在本 PR 范围):GitHub OAuth app 注册的 callback URL 是 localhost:3000/api/auth/callback/github,前端换端口跑(如本机 3010)时需要 到 GitHub OAuth app 里补一条 callback URL,否则授权回来依旧 404。
1 parent 7b74f11 commit 83c6c52

2 files changed

Lines changed: 12 additions & 5 deletions

File tree

app/components/SignInButton.tsx

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,13 @@ interface SignInButtonProps {
77
}
88

99
export function SignInButton({ className }: SignInButtonProps) {
10-
// 直接跳转到后端 GitHub OAuth 授权入口(NEXT_PUBLIC_BACKEND_URL)
11-
// 后端完成授权后带着 token 重定向回前端首页 /#token=xxx(fragment,不会出现在服务器日志中)
10+
// 同源跳到 /oauth/render/github,经 next.config.mjs 的 rewrite 代理到后端。
11+
// 好处:开发环境后端端口改来改去(8080 / 8081)都不用改前端;302 由 Next.js 透传给浏览器,
12+
// 最终由浏览器跳到 GitHub 授权页。
13+
// 注意:GitHub OAuth app 注册的 callback URL 决定最终返回的前端端口
14+
// (当前注册为 localhost:3000/api/auth/callback/github),换端口跑本地时需在 GitHub OAuth app 里补一个。
1215
const handleSignIn = () => {
13-
const backendUrl =
14-
process.env.NEXT_PUBLIC_BACKEND_URL ?? "http://localhost:8080";
15-
window.location.href = `${backendUrl}/oauth/render/github`;
16+
window.location.href = "/oauth/render/github";
1617
};
1718

1819
return (

next.config.mjs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,12 @@ const config = {
4141
source: "/api/user-center/:path*",
4242
destination: `${backendUrl}/api/user-center/:path*`,
4343
},
44+
{
45+
// OAuth 跳转入口(/oauth/render/github),走 rewrite 让前端不感知后端端口
46+
// 后端返回 302 到 GitHub 授权页,Next.js 透传 302 给浏览器完成跳转
47+
source: "/oauth/:path*",
48+
destination: `${backendUrl}/oauth/:path*`,
49+
},
4450
];
4551
},
4652
images: {

0 commit comments

Comments
 (0)