Mac版Safari登录API返回401错误求助(Next.js项目)
问题背景
基于Next.js开发的网站,登录认证机制在除Mac版Safari外的所有浏览器中正常运行,但在Mac版Safari调用API时返回401错误。已确认请求头包含Authorization: token,API本身无问题(其他浏览器可正常调用)。尝试过的解决方案包括:在URL末尾添加/、设置Cookie时配置secure: true和SameSite:"Strict",但问题仍未解决,且无法控制或访问后端代码。
前端提交代码
const handleSubmit = async () => { setLoading(true) // event.preventDefault(); const data = { phone: userNumber, otpCode: finalOtp }; try { // Make the POST request using Axios const response = await axios.post('https://myapi-domain/api/auth/otpVerify/', data); const expirationTime = 4; // in hours const now = new Date(); now.setTime(now.getTime() + expirationTime * 60 * 60 * 1000); Cookies.set("jazz_token", response.data.access_token, { expires: now , secure: true , SameSite:"Strict" }); setLoading(false) handleOtpMessage('success',response.data.message) window.location.href= '/' } catch (error) { // Handle any errors that occurred during the request const typedError = error as ErrorResponse; console.error('Error:', typedError.response.data.message); // Swal.fire(typedError.response.data.message); handleOtpMessage('error',typedError.response.data.message) setOtp1('') setOtp2('') setOtp3('') setOtp4('') setLoading(false); } };
排查与解决方案
调整Cookie的SameSite属性:
Mac版Safari对SameSite: Strict的兼容性存在特殊处理,尤其是跨域场景下。尝试将SameSite:"Strict"改为SameSite:"Lax",同时添加path: '/'确保Cookie在全站路径下可访问:Cookies.set("jazz_token", response.data.access_token, { expires: now, secure: true, SameSite: "Lax", path: '/' });确保Axios自动携带跨域Cookie:
如果API请求属于跨域场景,Axios默认不会自动携带Cookie,需在请求中添加withCredentials: true配置:const response = await axios.post('https://myapi-domain/api/auth/otpVerify/', data, { withCredentials: true });检查Safari隐私设置:
提示用户检查Safari偏好设置中的「隐私」选项,确认未开启「阻止跨站跟踪」或「阻止所有Cookie」,确保网站可以正常设置和读取Cookie。验证Cookie读取逻辑:
若后续API请求是从Cookie中读取token并添加到Authorization头,可在Safari控制台执行Cookies.get("jazz_token")验证是否能正常读取。若无法读取,需确认Cookie的属性配置是否符合Safari要求。Next.js SSR场景适配:
如果项目使用服务器端渲染(SSR),确保在客户端组件中处理认证逻辑;若需在服务器端读取Cookie,使用Next.js提供的next/headers中的cookies()函数进行读取,避免兼容性问题。
内容的提问来源于stack exchange,提问作者Prashant Singh

