我的回答是基于我的个人经验。我自己也在后端使用 Express.js API 运行 Next.js。我相信用 Vercel 托管您的前端并用 Heroku 托管您的自定义 API 也是一个合乎逻辑的提议,因为 Heroku 可以接受更大的有效负载并且专用于托管您的 API,这与 Vercel 仅服务于前端(和 Next .js 无服务器 API(如果可用)。
但是,您可能需要调整您的授权(如果有的话),使其适合您的用例。请记住,cookie 不能跨域发送。换句话说,从 Heroku 后端直接向 Next.js 前端发送一个 cookie 是不可能的,除非你做了几个变通方法,我现在都不知道。
我的解决方法是,您实际上可以使用 Next.js 无服务器 API作为代理将您的授权请求发送到您的自定义 API。
例如,我将提供登录用户的方式,以展示如何使用 Next.js 的无服务器 API 和您的自定义 API 实现跨域 cookie。我将假设您将使用 JWT 作为对用户进行身份验证的方法。
// auth.js -> in your custom server
const userToken = await yourAuthorizationFunction();
// Send the token as an API response to your Next.js Serverless proxy.
res.status(200).json({
status: 'success',
token: userToken,
});
下面是从 Next.js API 获取 cookie 的方法。
// web/pages/myAuthentication.js -> your Next.js serverless API
import axios from 'axios';
import Cookies from 'cookies';
export default async (req, res) => {
// 1. Receive the cookies here.
const response = await axios.post(YOUR_ENDPOINT_TO_GET_COOKIES);
// 2. Set the JWT (or your token) to be used in the front-end.
const cookies = new Cookies(req, res);
cookies.set('jwt', response.data.token, {
httpOnly: true,
expires: new Date(Date.now() + 24 * 60 * 60 * 1000),
sameSite: 'lax',
});
// 3. Send success, cookie has been set.
res.status(200).json({
status: 'success',
});
};
如果你想发出 POST 请求,你可以简单地从你的前端获取 cookie(如果你没有将 cookie 方法设置为 httpOnly 或者如果你使用 withCredentials 设置为 true),或者您可以再次调用您的代理 API,将所有数据传送到您的自定义服务器。