Auth.js

거의 만능에 가까운 인증 오픈소스로 단 몇 분 안에 인증 서비스를 추가할 수 있다.

Next.js 에서의 사용

npm install next-auth@beta @auth/core

auth.ts

import NextAuth from "next-auth"
import GitHub from "next-auth/providers/github"

export const {
  handlers: { GET, POST },
  auth,
} = NextAuth({
  providers: [GitHub],
})

middleware.ts

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

export async function middleware() {
  const session = await auth();
  if (!session) {
    return NextResponse.redirect('<http://localhost:3000/i/flow/login>');
  }
}

// matcher에 해당하는 라우트들에서는 middleware 함수가 페이지 렌더링되기전에 실행
// 즉, 만약 로그인을 했으면 통과, 그렇지 않으면 로그인페이지로 리다이렉트.
export const config = {
  matcher: ['/compose/tweet', '/home', '/explore', '/messages', '/search'],
};

next13이후(app router도입)이후 미들웨어 기능을 지원함에 따라 앱라우터에서는 페이지 접근 권한에 따라 관리를 하기가 더 쉬워졌습니다.

Routing: Middleware

Auth.js