Next.jsにAuth.jsを導入、セットアップしてJWT認証のバックエンドと連携させる手順を書きます。
Auth.jsのセットアップ
まずは、Next.jsでAuth.jsが使用できるようにセットアップしていきます
step.1 Next.jsにAuth.jsをインストール
Next.jsのプロジェクト直下で下記を実行してインストールしてください
npm install next-auth@beta
step.2 AUTH_SECRETパラメータの作成
Next.jsのプロジェクト直下で下記を実行してAUTH_SECRETパラメータを作成します
npx auth secret
作成されたパラーメータを.envファイルに記載際ます。
デフォでは.envは存在しないので、Next.jsのプロジェクト直下で作成してください。
そして、このように記載しておきます。
AUTH_SECRET="fd38b52eebedd ・・・省略"
step.3 auth.tsファイルの作成
Next.jsのプロジェクト直下に、auth.tsファイルを作成します。
そして、中身をこのように編集。
import NextAuth from "next-auth"
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [],
})
step.4 route.tsファイルの作成
src/appの中に、api/auth/[...nextauth]のフォルダを作ります。

そして、[...nextauth]のフォルダ直下にroute.tsを作成します。
import { handlers } from "../../../../../authの部分は先ほど作成したauth.tsの呼び出しです。
import { handlers } from "../../../../../auth" // Referring to the auth.ts we just created
export const { GET, POST } = handlers
step.5 proxy.tsの作成
Next.jsのプロジェクト直下に、proxy.tsファイルを作成します。
そして、中身をこのように編集。
export { auth as proxy } from "./auth"
ここまでで、auth.jsを使用するための基本のセットアップは完了です。
ログイン処理
laravel、django、rails、Spring Bootなどのバックエンドに通信してログインできる処理をします。
これを実現するには、auth.tsに手を加えます。
例で、強制的にログイン成功させる処理を書いてますが
実際には、バックエンドのエンドポイントにfetchで通信して、その結果(ユーザー情報)を返すロジックを書く必要があります。
import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { use } from "react"
import signInGetUser from "@/feature/signInGetUser"
//テスト用ログイン関数
function getUserFromDb({email,password}:{email:string|unknown,password:string|unknown}){
//固定のユーザー情報を返している
return{
email: "ts@ta.com",
image: "",
name: "test",
}
}
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Credentials({
// You can specify which fields should be submitted, by adding keys to the `credentials` object.
// e.g. domain, username, password, 2FA token, etc.
credentials: {
email: {},
password: {},
},
authorize: async (credentials) => {
let user = null
//ここにバックエンドの認証処理を書きます
user = await getUserFromDb({
email:credentials.email,
password:credentials.password
})
//ユーザーが見つからない
if (!user) {
throw new Error("Invalid credentials.")
}
// return user object with their profile data
return user
},
}),
],
})
参考
ユーザー情報を取得してページで表示する場合は、ここが参考になりそうです