Next.js跳转SSO登录页时如何获取当前URL实现认证后回跳
Next.js 服务端获取当前页面URL的实现方案
Pages Router 场景(基于 getServerSideProps)
直接从 getServerSideProps 的上下文参数中提取请求信息拼接完整URL即可:
export async function getServerSideProps(context) { const host = context.req.headers.host; // 可根据实际部署环境调整协议判断逻辑 const protocol = process.env.NODE_ENV === 'development' ? 'http' : 'https'; // 拼接完整URL并做URL编码,避免参数解析异常 const currentUrl = encodeURIComponent(`${protocol}://${host}${context.req.url}`); return { redirect: { destination: `/sso/form?redirect=${currentUrl}`, permanent: false, }, } }
context.req.url仅包含当前页面的路径与查询参数,拼接host和协议后才能得到可直接跳转的完整URL- 必须使用
encodeURIComponent对URL进行编码,避免特殊字符导致SSO端解析redirect参数出错
App Router 场景
服务端组件/路由处理函数中使用
可通过Next.js提供的headers方法获取请求头信息拼接:
import { headers } from 'next/headers'; export default async function ProtectedPage() { const headersList = headers(); const host = headersList.get('host'); const protocol = process.env.NODE_ENV === 'development' ? 'http' : 'https'; const fullPath = `${headersList.get('x-next-pathname') || ''}${headersList.get('x-next-search') || ''}`; const currentUrl = encodeURIComponent(`${protocol}://${host}${fullPath}`); // 后续重定向逻辑 }
Middleware中使用
直接从request对象直接获取完整URL即可:
import { NextResponse } from 'next/server'; export function middleware(request) { const currentUrl = encodeURIComponent(request.nextUrl.href); return NextResponse.redirect(new URL(`/sso/form?redirect=${currentUrl}`, request.url)); }
内容的提问来源于stack exchange,提问作者Alexandre
相关产品推荐
相关产品推荐

