From 450975607bb7f6cc14abf13e4ea541503dab318f Mon Sep 17 00:00:00 2001 From: Lim dong hyeon Date: Sat, 1 Jun 2024 01:47:38 +0900 Subject: [PATCH] =?UTF-8?q?[#39]=20Feat:=20middleware=20=EC=84=A4=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware.ts | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 middleware.ts diff --git a/middleware.ts b/middleware.ts new file mode 100644 index 00000000..22b17f09 --- /dev/null +++ b/middleware.ts @@ -0,0 +1,43 @@ +import { NextResponse } from 'next/server'; +import type { NextRequest } from 'next/server'; + +const PROTECTED_PAGES = ['/start-family']; +const PUBLIC_PAGES = ['/login']; + +export default function middleware(request: NextRequest) { + const { cookies, nextUrl } = request; + const path = nextUrl.pathname; + const isProtectedPage = PROTECTED_PAGES.includes(path); + const isPublicPage = PUBLIC_PAGES.includes(path); + + // 로그인 상태 확인 + const hasCookie = cookies.has('accessToken'); + + // 쿼리 파라미터에서 token 값 확인 + const hasToken = nextUrl.search.includes('token'); + + // /start-family 페이지로 접근하는데 token이 있을 경우 진행 + // /start-family 페이지로 접근하는데 token이 없을 경우 리다이렉션 + // 추후 배포됐을 때 수정. + if (path === '/start-family' && hasToken) { + return NextResponse.next(); + } else if (path === '/start-family' && !hasToken) { + return NextResponse.redirect(new URL('/login', request.nextUrl)); + } + + // 비로그인 상태일 때 로그인이 필요한 페이지에 접근 시 리다이렉션 + if (!hasCookie && isProtectedPage) { + return NextResponse.redirect(new URL('/login', request.nextUrl)); + } + + // 로그인 상태일 때 로그인 페이지에 접근 시 리다이렉션 + if (hasCookie && isPublicPage) { + return NextResponse.redirect(new URL('/', request.nextUrl.origin)); + } + + return NextResponse.next(); +} + +export const config = { + matcher: ['/login', '/start-family'], +};