英文:
using iron-session with NextJS and the new app router
问题
抱歉我的无知...我对会话cookie和身份验证没有完全掌握,这就是为什么我正在构建一个东西...以理解,然后做得更好...
无论如何,我正试图在我的nextJS应用程序上启用会话cookie,并且正在移植来自iron session的示例代码...然而,iron session的示例使用了页面路由,而我在我的应用程序中没有使用。
例如,这是iron sessions示例中的登录路由:
import { Octokit } from "octokit";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "lib/session";
const octokit = new Octokit();
export default withIronSessionApiRoute(async (req, res) => {
const { username } = await req.body;
try {
const {
data: { login, avatar_url },
} = await octokit.rest.users.getByUsername({ username });
const user = { isLoggedIn: true, login, avatarUrl: avatar_url };
req.session.user = user;
await req.session.save();
res.json(user);
} catch (error) {
res.status(500).json({ message: error.message });
}
}, sessionOptions);
你可以在以下链接看到我参考的完整代码:https://github.com/vvo/iron-session
跟随/examples/next.js/
现在,我面临的问题是,nextJS中的应用程序路由需要一个POST()或GET()函数才能正常工作,而我不太了解withIronSessionApiRoute()是如何包装在路由周围的。
我已经广泛查阅了关于此的nextJS文档,但在将页面路由迁移到应用程序路由方面没有找到太多信息。有什么建议或想法吗?
我希望这个问题表达得清楚,如果不清楚的话,请随时提出澄清性问题。
一如既往,感谢!
Chris Roode
英文:
Pardon my ignorance...I don't have a 100% grasp of session cookies, and authentication, which is why I am building something...to understand, then to do better...
Anyway, I am trying to get session cookies going on my nextJS app, and I am porting in the sample code from iron session...however, the examples of iron session use the pages router, which I am not using in my application.
For example, here's the login route from iron sessions examples:
import { Octokit } from "octokit";
import { withIronSessionApiRoute } from "iron-session/next";
import { sessionOptions } from "lib/session";
const octokit = new Octokit();
export default withIronSessionApiRoute(async (req, res) => {
const { username } = await req.body;
try {
const {
data: { login, avatar_url },
} = await octokit.rest.users.getByUsername({ username });
const user = { isLoggedIn: true, login, avatarUrl: avatar_url };
req.session.user = user;
await req.session.save();
res.json(user);
} catch (error) {
res.status(500).json({ message: error.message });
}
}, sessionOptions);
You can see the full code I'm referencing at: https://github.com/vvo/iron-session
follow /examples/next.js/
Right now, the problem I'm facing is that the app router in nextJS wants a POST() or GET() function for it to work properly, and I dont' have a complete grasp of how withIronSessionApiRoute() is wrapping itself around the routing.
I've looked extensively at the nextJS documentation around this, but haven't found much in migrating pages router to app router. Any suggestions or thoughts?
I hope this question comes across cleary, if not, feel free to ask clarifying questions.
As always, thanks!
Chris Roode
答案1
得分: 1
I recently migrated an application to the app router, the withIronSessionSsr method is just a wrapper for easier use, to achieve the same functionality you can just leverage the low level seal/unseal methods. Something like this (in a server component):
import { unsealData } from 'iron-session/edge';
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = cookies();
const encryptedSession = cookieStore.get('name-of-your-cookie')?.value;
const session = encryptedSession
? await unsealData(encryptedSession, {
password: 'your-password',
})
: null;
return <div>{session ? session.some_value : 'not authenticated'}</div>;
}
Creating the session can be tricky since you need to set the encrypted session with a cookie header either in a route handler or a middleware.
import { sealData } from 'iron-session/edge';
// endpoint to log in a user
export async function POST() {
const session = JSON.stringify({
userId: 1,
name: 'john doe',
});
const encryptedSession = sealData(session, {
password: 'your-password',
});
return new Response('ok', {
status: 200,
headers: { 'Set-Cookie': `name-of-your-cookie=${encryptedSession}` },
});
}
Credits: https://github.com/vvo/iron-session/issues/594#issuecomment-1638964195
英文:
I recently migrated an application to the app router, the withIronSessionSsr method is just a wrapper for easier use, to achieve the same functionality you can just leverage the low level seal/unseal methods. Something like this (in a server component):
import { unsealData } from 'iron-session/edge';
import { cookies } from 'next/headers';
export default async function Page() {
const cookieStore = cookies();
const encryptedSession = cookieStore.get('name-of-your-cookie')?.value;
const session = encryptedSession
? await unsealData(encryptedSession, {
password: 'your-password',
})
: null;
return <div>{session ? session.some_value : 'not authenticated'}</div>;
}
Creating the session can be tricky since you need to set the encrypted session with a cookie header either in a route handler or a middleware.
import { sealData } from 'iron-session/edge';
// endpoint to log in a user
export async function POST() {
const session = JSON.stringify({
userId: 1,
name: 'john doe',
});
const encryptedSession = sealData(session, {
password: 'your-password',
});
return new Response('ok', {
status: 200,
headers: { 'Set-Cookie': `name-of-your-cookie=${encryptedSession}` },
});
}
Credits: https://github.com/vvo/iron-session/issues/594#issuecomment-1638964195
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论