我正在尝试获取当前用户 ID,以将其推送到使用 mongodb 创建文档中。
我创建了一个特定的 APi 路由,它从表单获取数据。 但是,我无法像在基本 React 组件中那样使用 useSession 在 API 路由中获取 session.user.id 。那么我应该如何继续检索当前的用户 ID?
这是 api/companies/create.js 的当前代码:
import { MongoClient } from "mongodb";
// import clientPromise from "../../../lib/mongodb";
async function handler(req, res) {
if (req.method === "POST") {
const { name, bio, size, location, logo, website, industry } = req.body;
// | (bio.trim() === "")
// BACKEND VALIDATION
if (!name || name.trim() === "") {
res.status(422).json({ message: "Invalid input." });
return;
}
// Storing it in the database
const newCompany = {
name,
size,
bio,
location,
logo,
website,
industry,
};
let client;
try {
// const client = await clientPromise;
client = await MongoClient.connect(process.env.MONGODB_URI);
} catch (error) {
res.status(500).json({ message: "Could not connect to database." });
return;
}
const db = client.db("main");
try {
const result = await db.collection("companies").insertOne(newCompany);
// Not sure about that line:
// newCompany.id = result.insertedId;
} catch (error) {
client.close();
res.status(500).json({ message: "Storing message failed!" });
return;
}
client.close();
res.status(201).json({ message: "Sucessfuly stored company" });
}
}
export default handler;
这来自:https://next-auth.js.org/configuration/nextjs
这就是我在 API 路由中在服务器端获取会话的方式
import type { NextApiRequest, NextApiResponse } from 'next'
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "../auth/[...nextauth]"
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const session = await unstable_getServerSession(req, res, authOptions)
// you can now use session.data
我认为 NextAuth 最终希望您使用中间件来控制某些 API 路由并将会话相关数据传递给 API 功能。
使用 get 方法和 Cookie 标头请求 api 路由
获取http://localhost:3000/api/users/me
内容类型:application/json
Cookie: authjs.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoiVjVIOVJVaWNRekZmel9tTG53MWRIdkQ4VEZHSUVwMVh4eExTR0hUNDlySm50MDlPWER1QUx1RWk5LXFaN1FjYmg1UH hkdlFzYTVKcHl5Ymh3QmM4cncifQ..Ij0Jwjg0SNVThbaYQBll2Q.x8xQG0GDR24d-30v 60Yvn0PS8xB83ALxvq9e6Wjd09wWdYv5A_UFj50VWfB2nyWJNWpM1NNDnDf36AJ-SIFcfQ YhO-FPYDqJuAGiXR7xkOp5P5zjfWsBtcYus7B9sKjxOySqun5jJgRjUFlfdmNM0EeQwhahnZA1UF3P7F7gYxUdAwNNho7oIdAzfKl5pVX4UJlEmXIQIq1WzDiyKOegTtUL_1Q_73ihE1jLE Z8KCH4.x4vC7VU7AqWl-bCpZgsF_zNFZxH8UMPdDJgqM2KCW8A
或使用授权标头代替 Cookie 标头
两者使用 getToken() 方法给出相同的结果。
获取http://localhost:3000/api/users/me
内容类型:application/json
Authorization: Bearer eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoiVjVIOVJVaWNRekZmel9tTG53MWRIdkQ4VEZHSUVwMVh4eExTR0hUNDlySm50MDlPWER1QUx1RWk5LXFaN1FjYmg1UHhkdlFzYTVKcHl5Ymh3QmM4cncifQ..YvAhcAXk33nSk5yM_wLegA.G4hi9yUKMptH42H-rDgWs2zLbzrTPCnY5Acb9p1siEBdrcL5vFMlZabA9SUdd2JX5vQgCP6XMJ5OX4omS6VxRepzmJwHNnQE06s3A7VdmBR99muzVuDhO8C9GEKQMHmY5eNHB9eB5m_32GiYcgnM3dFkXpkulQNWLGab5FFI_dSNYm68ld_ualUes0WzemlGzfI3mfre6gY1PUctgQQyBmiR7HrMP9UDB_qDWOSrTbQ.Pv2brSg6PkdgEavd8au3KM22gMOeSLjzcfWAnk0v1Us
import { getToken } from 'next-auth/jwt';
export const GET = async (req: Request) => {
try {
// Your NEXTAUTH_SECRET
const secret = 'UWAoKYAU3nTuj1IAUO6EN4CYSspoudFbXDFJiQoje3s=';
// Decrypted payload from token
const payload = await getToken({ req, secret } as any) as any;
console.log(payload);
// {
// name: 'Grogu',
// email: '[email protected]',
// sub: 'e69d6716-f22f-4c60-9cee-f5adb1247965',
// iat: 1715296797,
// exp: 1715469597,
// jti: '84713b78-c5af-48c4-a051-1721cb623bdd'
// }
const body = {
success: true,
data: {
username: payload.name,
id: payload.sub,
email: payload.email
}
};
return Response.json(body, { status: 200 });
} catch (error) {
const body = {
success: false,
data: null
};
return Response.json(body, { status: 500 });
}
};
使用此功能,您可以通过发送带有 Cookie 标头的请求来获取 API 路由中的会话信息。
使用 get 方法和 Cookie 标头请求 api 路由
获取http://localhost:3000/api/users/me
内容类型:application/json
Cookie: authjs.session-token=eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2Q0JDLUhTNTEyIiwia2lkIjoiVjVIOVJVaWNRekZmel9tTG53MWRIdkQ4VEZHSUVwMVh4eExTR0hUNDlySm50MDlPWER1QUx1RWk5LXFaN1FjYmg1UH hkdlFzYTVKcHl5Ymh3QmM4cncifQ..Ij0Jwjg0SNVThbaYQBll2Q.x8xQG0GDR24d-30v 60Yvn0PS8xB83ALxvq9e6Wjd09wWdYv5A_UFj50VWfB2nyWJNWpM1NNDnDf36AJ-SIFcfQ YhO-FPYDqJuAGiXR7xkOp5P5zjfWsBtcYus7B9sKjxOySqun5jJgRjUFlfdmNM0EeQwhahnZA1UF3P7F7gYxUdAwNNho7oIdAzfKl5pVX4UJlEmXIQIq1WzDiyKOegTtUL_1Q_73ihE1jLE Z8KCH4.x4vC7VU7AqWl-bCpZgsF_zNFZxH8UMPdDJgqM2KCW8A
import { auth } from '@/lib/auth';
// { auth } is from your auth.ts where export is like this:
// export const { handlers, signIn, signOut, auth } = NextAuth(authOptions);
// in other words, you can get it by destructing 'NextAuth(authOptions)'
export const GET = async (req: Request) => {
try {
// Session info
const session = await auth() as any;
console.log(session);
// user: {
// name: 'Grogu',
// email: '[email protected]',
// id: 'e69d6716-f22f-4c60-9cee-f5adb1247965'
// },
// expires: '2024-05-12T12:16:00.318Z'
const body = {
success: true,
data: {
username: session.user.name,
id: session.user.id,
email: session.user.email
}
};
return Response.json(body, { status: 200 });
} catch (error) {
const body = {
success: false,
data: null
};
return Response.json(body, { status: 500 });
}
};
注意:这也适用于服务器组件:
import { auth } from '@/lib/auth';
export default async function MainPage() {
const session = await auth();
console.log(session);
// user: {
// name: 'Grogu',
// email: '[email protected]',
// id: 'e69d6716-f22f-4c60-9cee-f5adb1247965'
// },
// expires: '2024-05-12T12:16:00.318Z'
return (
<div>
<pre>{JSON.stringify(session, null, 2)}</pre>
</div>
);
}