Open13

NextAuth触ってみる

tockiitockii

セットアップにSECRETの発行が必要なのか

npx auth secret
tockiitockii

CredentialsだとDBもいるからPrisma使うか
Adapterもあるっぽくて良い

https://authjs.dev/getting-started/adapters/prisma

tockiitockii

とりあえず今回はシンプルにユーザー情報とログインすると取れるデータのモデルを作成。Adapterは利用しない

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

model User {
    id             String   @id @default(cuid())
  name           String?
  email          String   @unique
  hashedPassword String
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt
}

model Data {
  id             String   @id @default(cuid())
  name           String?
  createdAt      DateTime @default(now())
  updatedAt      DateTime @updatedAt
}

tockiitockii

Email & Password は credentialsかな?

https://next-auth.js.org/providers/credentials

基本的には認証にはもっといい方法あるからそっち使ってねというスタンスっぽい

The industry has come a long way since usernames and passwords as the go-to mechanism for authenticating and authorizing users to web applications. Therefore, if possible, we recommend a more modern and secure authentication mechanism such as any of the OAuth providers, Email Magic Links, or WebAuthn (Passkeys) options instead.
However, we also want to be flexible and support anything you deem appropriate for your application and use case, so there are no plans to remove this provider.

tockiitockii

middlewareは自前で作るのが楽

import { NextResponse } from 'next/server';
import { auth } from '../auth';

export default auth((req) => {
  if (req.nextUrl.pathname === '/user') {
    if (!req.auth) {
      const url = new URL('/auth/signin', req.url);
      return NextResponse.redirect(url);
    }
  }
  return NextResponse.next();
});