반응형
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
Routing: Redirecting | Next.js
Learn the different ways to handle redirects in Next.js.
nextjs.org