1. reference
Backend – API Route
To protect an API Route, you can use the unstable_getServerSession() method.
https://next-auth.js.org/getting-started/example#backend—api-route
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./auth/[...nextauth]"
export default async (req, res) => {
const session = await unstable_getServerSession(req, res, authOptions)
if (session) {
res.send({
content:
"This is protected content. You can access this content because you are signed in.",
})
} else {
res.send({
error: "You must be signed in to view the protected content on this page.",
})
}
}
2. そのままでは動かない
3. point
import { authOptions } from "./auth/[...nextauth]"
^^^^^^^^^^^^^^^
4. Change code at ‘pages/api/auth/[…nextauth]’
– export const authOptions: NextAuthOptions = {
– export default NextAuth(authOptions);
import { NextAuth } from 'next-auth'
import type { NextAuthOptions } from 'next-auth'
export const authOptions: NextAuthOptions = {
providers: [
GithubProvider({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
callbacks: {
async signIn({ user, account, profile, email, credentials }) {
return true
},
async redirect({ url, baseUrl }) {
return baseUrl
},
async jwt({ token, account }) {
// Persist the OAuth access_token to the token right after signin
if (account) {
token.accessToken = account.access_token
}
return token
},
async session({ session, token, user }) {
// Send properties to the client, like an access_token from a provider.
session.accessToken = token.accessToken
return session
}
}
}
export default NextAuth(authOptions);
5. How to use with server code
– import
import { unstable_getServerSession } from "next-auth/next"
import { authOptions } from "./auth/[...nextauth]"
– in function
const session = await unstable_getServerSession(req, res, authOptions) console.log(session)
– console log
{
user: {
name: 'keybord cat',
email: 'k-cat@hogehoge.io',
image: 'https://avatars.githubusercontent.com/u/135275922?v=4'
},
expires: '2022-10-10T06:22:24.952Z',
accessToken: 'gho_kJ4Gl5uhnnPYuufMbmTWJQszhKcSBq0Lat22'
}
6. unstable_getServerSession ( google 翻訳 )
サーバー側、つまり API ルートまたは getServerSideProps から呼び出す場合は、getSession の代わりにこの関数を使用してセッション オブジェクトを取得することをお勧めします。 このメソッドは、データベースで NextAuth.js を使用している場合に特に便利です。 このメソッドを getSession サーバー側で使用すると、API ルートへの余分なフェッチが回避されるため、応答時間が大幅に短縮されます (これは通常、Next.js では推奨されません)。 さらに、unstable_getServerSession は Cookie の有効期限を正しく更新し、callbacks.jwt または callbacks.session が何かを変更した場合にセッションの内容を更新します。
7. WARRNING
This feature is experimental and may be removed or changed in the future.
とあるが,便利なので残してほしい