[Next.js 14] 1. Routing - 5

2025. 2. 5. 16:44·Skill/Next.js
반응형

6. Redirecting

  • Next.js에서 Redirct를 다룰 수 있는 몇 가지 방법이 있다.
API 사용 목적 사용 위치 Status Code
redirect Mutation or event 발생 후 사용자 redirect Server Components, Server Actions, Route Handler 307 or 303 (Server Action)
permanentRedirect Mutation or event 발생 후 사용자 redirect Server Components, Server Actions, Route Handler 308 (Permanent)
useRouter Client Side에서 Navigation 시 사용 Client Coponent 내의 Event Handler N/A
redirect in next.config.js URL Path의 접근에 따른 redirect next.config.js file 307 or 308 (Permanent)
NextResponse.redirect 들어오는 요청 조건에 따른 redirect Middleware Any
Mutation : 서버로의 CRUD 작업

6-1. redirect function

  • Server Components, Server Actions, Route Handler에서 사용할 수 있는 사용자 redirect 함수.
'use server'
 
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
 
export async function createPost(id: string) {
  try {
    // Call database
  } catch (error) {
    // Handle errors
  }
 
  revalidatePath('/posts') // Update cached posts
  redirect(`/post/${id}`) // Navigate to the new post page
}
  • revalidatePath 함수는 해당 경로의 세그먼트에 남아있는 기존 Cache를 삭제하여 최신화 하는 것.

6-2. permanentRedirect function

  • Redirect가 임시적인 URL 이동이면, Permanent Redirect는 영구적인 URL 이동이다.
  • Server Components, Route Handlers, Server Actions에서 사용이 가능.
  • 기존 URL이 유효하지 않을 때, 사용 한다.
'use server'
 
import { permanentRedirect } from 'next/navigation'
import { revalidateTag } from 'next/cache'
 
export async function updateUsername(username: string, formData: FormData) {
  try {
    // Call database
  } catch (error) {
    // Handle errors
  }
 
  revalidateTag('username') // Update all references to the username
  permanentRedirect(`/profile/${username}`) // Navigate to the new user profile
}
1. permanentRedirect function은 기본적으로 308 Code를 반환.
2. 절대 경로 URL과 외부 URL 연결이 가능.
3. 렌더링 전에 redirect 시키고 싶으면 next.config.js or Middleware 사용.

redirect와 permanentRedirect의 구분하는 이유는 기존 URL을 인덱싱하는 SEO, 새로운 URL을 계속 서버를 통해 확인하는 브라우저 캐싱 등의 문제가 있기 때문이다.
-> 긍까 더 이상 유효하지 않는 URL일 거 같으면 permanentRedirect 써라. (도메인 또는 URL 구조 변경 등..)

6-3. useRouter() hook

  • Client Component 내의 Event Handler에서 redirect 시키고 싶으면 useRouter의 push 함수를 사용.
'use client'
 
import { useRouter } from 'next/navigation'
 
export default function Page() {
  const router = useRouter()
 
  return (
    <button type="button" onClick={() => router.push('/dashboard')}>
      Dashboard
    </button>
  )
}
  • 프로그래밍 적으로 필요한 경우가 아니라면, <Link> 컴포넌트를 사용.

6-3. redirects in next.config.js

  • next.config.js 내 redirects 옵션을 사용하면, 특정 Path로 접근하는 경우 다른 Path 목적지로 redirect 시킬 수 있다.
  • path, header, cookie, query matching 등을 활용할 수 있다.
module.exports = {
  async redirects() {
    return [
      // Basic redirect
      {
        source: '/about',
        destination: '/',
        permanent: true,
      },
      // Wildcard path matching
      {
        source: '/blog/:slug',
        destination: '/news/:slug',
        permanent: true,
      },
    ]
  },
}
1. redirect는 기본 307 Status Code를 반환하지만, permanent true 인 경우 308 Status Code를 가진다.
2. 플랫폼에 따라 redirect의 제한이 있을 수 있다. 증가시키고 싶으면 Middleware를 사용하거나 다른 방법이 필요.
3. redirects는 Middleware 이전에 실행된다.

6-4. NextResponse.redirect in Middleware

  • Middleware는 요청이 완료되기 전에 코드를 실행시킬 수 있다.
  • 요청에 따라 NextResponse.redirect를 이용해 다른 URL로 redirect 시킬 수 있다. (사용자 권한에 따른 조건부 redirect.)
import { NextResponse, NextRequest } from 'next/server'
import { authenticate } from 'auth-provider'
 
export function middleware(request: NextRequest) {
  const isAuthenticated = authenticate(request)
 
  // If the user is authenticated, continue as normal
  if (isAuthenticated) {
    return NextResponse.next()
  }
 
  // Redirect to login page if not authenticated
  return NextResponse.redirect(new URL('/login', request.url))
}
 
export const config = {
  matcher: '/dashboard/:path*',
}
Middleware는 next.config.js의 redirects 이후, 렌더링 전에 실행된다.

처음 뵙겠습니다.

Next.js 사용하면서 처음 본 개념이거나, 이해하기 어려운 부분(?)은 붉은색 볼드처리 해봤다.

1. Mutation: 서버로의 CRUD 작업을 의미 한다고 한다. 이게 끝??? 더 찾아봐야 겠다.

2. Route Handler: Next.js 서버와 HTTP 통신을 하는 것? 같다.

 

Preference

  • https://nextjs.org/docs/14/app/building-your-application/routing/redirecting
 

Routing: Redirecting | Next.js

Learn the different ways to handle redirects in Next.js.

nextjs.org

 

 

 

 

 

 

저작자표시 (새창열림)
'Skill/Next.js' 카테고리의 다른 글
  • [Next.js 14] 1. Routing - 7
  • [Next.js 14] 1. Routing - 6
  • [Next.js 14] 1. Routing - 4
  • [Next.js 14] 1. Routing - 3
뜸부깅
뜸부깅
코딩에 대한 여러 개인적인 생각을 정리하고 공부를 하는 공간입니다!!
  • 뜸부깅
    코오오딩
    뜸부깅
  • 전체
    오늘
    어제
    • Note (429)
      • Skill (31)
        • Java & Spring (9)
        • Javascript & HTML & CSS (0)
        • React (0)
        • Next.js (22)
      • CodingTest (389)
        • 백준 온라인 저지(BOJ) (140)
        • 프로그래머스(Programmers) (79)
        • LeetCode (170)
      • Algorithm & Data Structure (6)
      • [Project] 포트폴리오 (3)
        • Front end (3)
        • Back end (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    Java
    백준1260
    Easy
    BOJ
    자바
    boj1427
    meidum
    component-scan
    boj2108
    백준7576
    백준
    백준7576자바
    백준1427
    백준2751
    TypeScript
    next 14
    프로그래머스
    leetcode 2236
    알고리즘
    medium
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
뜸부깅
[Next.js 14] 1. Routing - 5
상단으로

티스토리툴바