0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【2026年版】Next.jsにAuth.jsをセットアップとemail &パスワードでログイン

0
Posted at

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のプロジェクト直下で作成してください。
そして、このように記載しておきます。

.env
AUTH_SECRET="fd38b52eebedd ・・・省略"

step.3 auth.tsファイルの作成

Next.jsのプロジェクト直下に、auth.tsファイルを作成します。
そして、中身をこのように編集。

auth.ts
import NextAuth from "next-auth"
 
export const { handlers, signIn, signOut, auth } = NextAuth({
  providers: [],
})

step.4 route.tsファイルの作成

src/appの中に、api/auth/[...nextauth]のフォルダを作ります。
image.png

そして、[...nextauth]のフォルダ直下にroute.tsを作成します。
import { handlers } from "../../../../../authの部分は先ほど作成したauth.tsの呼び出しです。

route.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ファイルを作成します。
そして、中身をこのように編集。

proxy.ts
export { auth as proxy } from "./auth"

ここまでで、auth.jsを使用するための基本のセットアップは完了です。

ログイン処理

laravel、django、rails、Spring Bootなどのバックエンドに通信してログインできる処理をします。
これを実現するには、auth.tsに手を加えます。

例で、強制的にログイン成功させる処理を書いてますが
実際には、バックエンドのエンドポイントにfetchで通信して、その結果(ユーザー情報)を返すロジックを書く必要があります。

auth.ts
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
            },
        }),
    ],
})

参考

ユーザー情報を取得してページで表示する場合は、ここが参考になりそうです

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?