[英]I am losing user information (session) on refreshing and between tabs while using iron-session and next.js
我目前正在使用 iron-session 和 next.js 进行一个项目。我不会在点击链接标签时失去我的用户。 但是如果我刷新用户变得不确定。 Cookie 已设置并且不会在刷新时被删除。 我不知道出了什么问题。
这是我的 login.ts 代码:
export default withIronSessionApiRoute(loginRoute, sessionOptions);
async function loginRoute(req: NextApiRequest, res: NextApiResponse) {
try {
const {
data: {tcId, admin, userName},
} = await axios('http://localhost:8080/user/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify(req.body),
});
const user = {tcId: tcId, userName: userName, admin: admin} as User;
req.session.user = user;
await req.session.save();
res.json(user);
} catch (error) {
res.status(500).json({message: (error as Error).message})
}}
这是我的 session.ts 代码:
// this file is a wrapper with defaults to be used in both API routes and `getServerSideProps` functions
import type { IronSessionOptions } from 'iron-session'
import type { User } from '../pages/api/user'
export const sessionOptions: IronSessionOptions = {
password: process.env.SECRET_COOKIE_PASSWORD as string,
cookieName: 'eys-cookie',
// secure: true should be used in production (HTTPS) but can't be used in development (HTTP)
cookieOptions: {
secure: process.env.NODE_ENV === 'production',
},
};
// This is where we specify the typings of req.session.*
declare module 'iron-session' {
interface IronSessionData {
user?: User
}
}
正如我之前所说。 我不会失去我的用户。 使用 next 中的Link标签进行路由。 刷新导致失去我的用户。 其他选项卡也无法到达我的用户。
如果需要,我可以显示更多代码。 但我认为问题就在这里。
我有一个类似的问题,并通过设置解决了选项卡切换:
revalidateOnFocus = false,
用于使用SWR function
样本
const fetcher = (url: any) => fetch(url).then((res) => res.json());
const options = {
revalidateOnFocus: false,
};
const {
data: session,
error,
mutate: mutateUser,
} = useSWR<Session>("/api/session", fetcher, options);
您还可以在此处探索其他选项https://swr.vercel.app/docs/options
Duno 如果你仍然有这个问题但可能你忘记在 de index 或 _app 组件上添加 SWRconfig
import { AppProps } from 'next/app'
import { SWRConfig } from 'swr'
import fetchJson from 'lib/fetchJson'
function MyApp({ Component, pageProps }: AppProps) {
return (
<SWRConfig
value={{
fetcher: fetchJson,
onError: (err) => {
console.error(err)
},
}}
>
<Component {...pageProps} />
</SWRConfig>
)
}
导出默认 MyApp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.