본문 바로가기

Study/NextJS 공식문서

[2주 차] Redirecting

redirect

redirect 함수는 사용자를 다른 URL로 리다이렉션 할 수 있게 한다. 리다이렉션은 Server Components, Route Handlers, Server Actions에서 호출할 수 있다. redirect는 일반적으로 mutation 또는 이벤트 후에 사용된다.

redirect 내부적으로 오류를 throw하기 때문에 try-catch 문 외부에서 호출해야한다. 또한, Client Components에서도 호출할 수 있지만, 이벤트 핸들러에서는 사용할 수 없다. 이벤트 핸들러에서는 대신 useRouter 훅을 사용해 리다이렉션을 구현해야 한다. redirect는 절대 URL도 허용하므로, 외부 링크로 리다이렉션하는 데 사용할 수 있다.
'use server'
 
import { redirect } from 'next/navigation'
import { revalidatePath } from 'next/cache'
 
export async function createPost(id: string) {
  try {
    // 데이터베이스 호출
  } catch (error) {
    // 에러 처리
  }
 
  revalidatePath('/posts') // 캐시된 게시물 업데이트
  redirect(`/post/${id}`) // 새 게시물 페이지로 이동
}

 

useRouter

클라이언트 컴포넌트의 이벤트 핸들러 내에서 리다이렉션 할 경우, 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>
  )
}

 

next.config.js 안에 redirects

next.config.js 파일의 redirects 옵션을 사용하면 들어오는 요청 경로를 다른 대상 경로로 리다이렉션 할 수 있다. redirects 옵션은 경로, 헤더, 쿠키, 및 쿼리 일치를 지원하여 들어오는 요청을 기반으로 사용자를 리다이렉션 할 수 있도록 도와준다.
// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/old-route',       // 리다이렉트할 기존 경로
        destination: '/new-route', // 리다이렉트될 대상 경로
        permanent: true,           // true: 308 상태 코드, false: 307 상태 코드
      },
    ];
  },
};
// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/product/:id',    // 동적 경로 (:id)
        destination: '/shop/:id', // 리다이렉트 대상 경로
        permanent: false,         // 임시 리다이렉션
      },
    ];
  },
};
// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/restricted',
        has: [
          {
            type: 'header',
            key: 'x-user-role',    // 헤더 이름
            value: 'guest',        // 헤더 값
          },
        ],
        destination: '/login',      // 헤더 조건에 맞으면 리다이렉트될 경로
        permanent: false,
      },
    ];
  },
};
// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/dashboard',
        has: [
          {
            type: 'cookie',
            key: 'isLoggedIn',    // 쿠키 이름
            value: 'false',       // 쿠키 값
          },
        ],
        destination: '/login',     // 쿠키 조건에 맞으면 리다이렉트될 경로
        permanent: false,
      },
    ];
  },
};
// next.config.js
module.exports = {
  async redirects() {
    return [
      {
        source: '/search',
        has: [
          {
            type: 'query',
            key: 'q',            // 쿼리 매개변수 이름
            value: '(.*)',       // 쿼리 값 (정규식 가능) (.*) => 모든 쿼리 값
          },
        ],
        destination: '/results?q=:q', // 리다이렉트 경로 :q => source의 쿼리 값
        permanent: false,
      },
    ];
  },
};

'Study > NextJS 공식문서' 카테고리의 다른 글

[3주 차] Project Organization  (0) 2025.01.19
[2주 차] Route Group  (0) 2025.01.11
[2주 차] Error Handling  (0) 2025.01.11
[2주 차] Loading UI and Streaming  (0) 2025.01.11
[2주 차] Linking and Navigating  (0) 2025.01.10