我正在使用使用云功能的自定义服务器托管我的 nextjs 站点。
const { https, logger } = require("firebase-functions");
const { default: next } = require("next");
const nextjsDistDir = require("../next.config.js").distDir;
const isDev = process.env.NODE_ENV !== "production";
const nextjsServer = next({
dev: isDev,
conf: {
distDir: nextjsDistDir,
},
});
const nextjsHandle = nextjsServer.getRequestHandler();
//The `nextApp` here is the Firebase Cloud Functions name
exports.nextApp = https.onRequest((req, res) => {
return nextjsServer.prepare().then(() => {
logger.info(req.path, req.query);
return nextjsHandle(req, res);
});
});
我有一个 AuthProvider,它应该监视 auth 状态的变化并设置一个包含 auth 令牌的 cookie
import nookies from 'nookies';
import firebase from "firebase/app";
import firebaseClient from "../scripts/firebaseClient";
import "firebase/auth";
import Cookies from 'js-cookie';
const AuthContext = createContext({});
export function AuthProvider({ children }) {
firebaseClient();
const [user, setUser] = useState(null);
// handle auth logic here...
// listen for token changes
// call setUser and write new token as a cookie
useEffect(() => {
return firebase.auth().onIdTokenChanged(async (user) => {
nookies.destroy(null, "token");
if (!user) {
setUser(null);
console.log("no user")
nookies.destroy(null, "token");
//nookies.set(undefined, 'token', '', { path: '/' });
document.cookie = `token=''; path=/`;
// Cookies.set("token", "");
return;
} else {
const token = await user.getIdToken();
setUser(user);
console.log("auth state token : "+token);
nookies.destroy(null, "token");
//console.log("auth user : "+token)
//nookies.set(undefined, 'token', token, { path: '/' });
// Cookies.set("token", token);
document.cookie = `token=${token}; path=/`;
return;
}
});
}, []);
//
// force refresh the token every 10 minutes
useEffect(() => {
const handle = setInterval(async () => {
const user = firebase.auth().currentUser;
if (user) await user.getIdToken(true);
}, 10 * 60 * 1000);
// clean up setInterval
return () => clearInterval(handle);
}, []);
return (
<AuthContext.Provider value={{ user }}>{children}</AuthContext.Provider>
);
};
export const useAuth = () => useContext(AuthContext);
然后我应该在 getServerSideProps
的页面中获取 cookie 并检查 cookie 中包含的令牌是否有效。
cookie 在生产中仅作为 undefined
出现。 cookie 'token' 在开发模式下可见。
有关此问题的所有其他问题都与生产中的 cookie 无关。
我可能做错了什么。
从上面的代码中可以看出,我尝试使用各种 cookie 包来设置 cookie,例如 nookies
、next-cookies
、cookies
等,它们都在开发模式下工作而不是在生产中