Nextjs中如何自动携带HttpOnly Cookie令牌请求Laravel API?
解决Next.js客户端请求Laravel API自动携带HttpOnly令牌的方案
方案一:用Next.js API路由做代理转发(推荐,保持HttpOnly安全性)
既然令牌存在HttpOnly Cookie里客户端拿不到,就让Next.js服务端帮你转发请求,自动带上Cookie。具体步骤:
- 创建动态代理路由:在
pages/api/proxy/[...path].js(App Router对应app/api/proxy/[...path]/route.js)编写代理逻辑:
// Pages Router版本 export default async function handler(req, res) { const { path } = req.query; const laravelApiBase = 'https://你的LaravelAPI地址.com'; const targetUrl = `${laravelApiBase}/${path.join('/')}`; try { // 转发请求到Laravel,自动携带当前请求的所有Cookie(包括HttpOnly令牌) const laravelRes = await fetch(targetUrl, { method: req.method, headers: { ...req.headers, host: new URL(laravelApiBase).host, // 替换host头避免CORS问题 'Content-Type': 'application/json', }, body: req.method !== 'GET' ? JSON.stringify(req.body) : undefined, credentials: 'include', }); // 将Laravel的响应头和内容原样返回给客户端 laravelRes.headers.forEach((val, key) => res.setHeader(key, val)); const data = await laravelRes.json(); res.status(laravelRes.status).json(data); } catch (err) { res.status(500).json({ error: '代理请求失败' }); } }
- 客户端请求调整:原来直接请求Laravel的
/user,现在改成请求Next.js的/api/proxy/user,完全不用处理令牌,Next.js会自动帮你带上HttpOnly Cookie。
方案二:改用非HttpOnly存储(适合对安全性要求稍低的场景)
如果可以放弃HttpOnly的安全性,把令牌存在localStorage或sessionStorage里,客户端请求时手动添加Authorization头:
- 登录时返回令牌给客户端:修改Next.js的登录API路由,把Laravel返回的令牌直接返回给前端,而非存在HttpOnly Cookie:
// pages/api/auth/login.js export default async function handler(req, res) { const { email, password } = req.body; const laravelRes = await fetch('https://你的LaravelAPI地址.com/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); const data = await laravelRes.json(); // 直接返回令牌给客户端 res.status(laravelRes.status).json(data); }
- 客户端存储并携带令牌:
// 登录逻辑 async function login(email, password) { const res = await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, password }), }); const { token } = await res.json(); localStorage.setItem('auth_token', token); } // 请求Laravel API时携带令牌 async function fetchUser() { const token = localStorage.getItem('auth_token'); const res = await fetch('https://你的LaravelAPI地址.com/user', { headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', }, }); return res.json(); }
⚠️ 注意:这种方式令牌容易被XSS攻击窃取,仅适合无敏感数据的场景,优先选择方案一。
方案三:用Next.js Middleware全局拦截转发
如果想更全局地处理请求,用Middleware拦截特定前缀的请求,自动转发到Laravel:
// middleware.js import { NextResponse } from 'next/server'; export function middleware(request) { // 匹配所有以/api/laravel/开头的请求 if (request.nextUrl.pathname.startsWith('/api/laravel/')) { const laravelPath = request.nextUrl.pathname.replace('/api/laravel/', ''); const targetUrl = new URL(`https://你的LaravelAPI地址.com/${laravelPath}`); // 克隆请求并转发,自动携带Cookie const proxyReq = new Request(targetUrl, { method: request.method, headers: request.headers, body: request.body, credentials: 'include', }); return NextResponse.rewrite(proxyReq); } } export const config = { matcher: '/api/laravel/:path*', };
客户端请求/api/laravel/user就会自动转发到Laravel的/user,无需额外处理令牌。
内容的提问来源于stack exchange,提问作者Mooder
相关产品推荐
相关产品推荐

