반응형
250x250
Notice
Recent Posts
Recent Comments
Link
관리 메뉴

짧은코딩

next-auth와 catch-all segments 본문

카테고리 없음

next-auth와 catch-all segments

5_hyun 2024. 3. 27. 19:59

next-auth(Auth.js)

https://authjs.dev/

 

Auth.js

Authentication for the Web.

authjs.dev

  • next-auth는 사실 이전 이름이고, 현재는 Auth.js로 바뀌었지만 이 글에선 next-auth라고 부르겠다.
  • next-auth는 next와 호환이 되는 로그인 라이브러리이다.
  • 또한 여러 sns 로그인도 지원해 준다.

-간단한 사용법

  1. 공식 문서를 보고 next-auth 설치
  2. app 폴더와 같은 위치에 auth.ts, middleware.ts 파일 생성 및 설정
  3. middleware.ts
    • next에서 middleware 기능을 제공해 줘서 로그인해야지만 접근 가능한 페이지를 쉽게 설정할 수 있음
    • 이것은 페이지 렌더링보다 middleware.ts에 있는 함수가 먼저 실행되기에 가능한 것
    • 따라서 middleware.ts의 config에 로그인해야 접근 가능한 페이지의 파일들을 적어주면 됨
  4. src/app/api/auth/[...nextauth]/route.ts에 로그인 api를 적어두고 사용하면 됨
  5. useSession을 통해 사용자 정보를 받아올 수 있는데, TS를 사용하면 속성을 id, name, email, image만 사용할 수 있다.
  6. AuthSesstion 컴포넌트를 만들고 사용하면, 어느 페이지에서든 로그인 여부를 쉽게 체크할 수 있다.

catch-all segments

https://nextjs.org/docs/pages/building-your-application/routing/dynamic-routes#catch-all-segments

 

Routing: Dynamic Routes | Next.js

Dynamic Routes are pages that allow you to add custom params to your URLs. Start creating Dynamic Routes and learn more here.

nextjs.org

  • 위에서 설명 중에 [...nextauth]이런 파일이 있다.
  • catch-all segment는 pages/shop/[...slug].js 이런 파일이 있으면 [...] 이 부분에 어떤 경로든 다 올 수 있다.

728x90
반응형
Comments