๐ก Issue : <Link /> ํ๊ทธ๋ฅผ ์ฌ์ฉํ ๋ ํ๋ฉด์ด ์ด๋ ํ๊ธฐ ์ , ์กฐ๊ฑด์ ๋ฐ๋ผ ํ๋ฉด ์ด๋์ ์ ์ด ํ๊ณ ์ถ๋ค๋ฉด?
๐ Middleware ๋ฅผ ์ฌ์ฉํ์!
Middleware
: request๋ฅผ ์๋ฃํ๊ธฐ ์ ์ ์ฝ๋๋ฅผ ์คํํ ์ ์๊ฒ ํด์ฃผ๋ ์ญํ .
๋ค์ด์ค๋ request์ ๋ฐ๋ผ, request ๋๋ ์๋ต ํค๋๋ฅผ ์ฌ์์ฑ, redirecting, ์์ ํ๊ฑฐ๋ ์ง์ ์๋ตํ์ฌ response๋ฅผ ์์ ํ ์ ์์ต๋๋ค.
Middleware๋ ์บ์๋ content์ ๊ฒฝ๋ก๊ฐ ์ผ์นํด์ง๊ธฐ ์ ์ ์คํ๋ฉ๋๋ค.
์ฌ์ฉ์๋ฅผ ๋ค๋ฅธ ํ์ด์ง๋ก ์ด๋ ์ํค๊ธฐ ์ํ ๋ชฉ์ ์ด ์๊ฑฐ๋ ์ธ์ฆ์ด ํ์ํ ๋, Middleware๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ์ผ๋ฐ์ ์ด๋ค.
๐๐ผ <Link /> ์ปดํฌ๋ํธ๊ฐ ๋ฏธ๋ค์จ์ด๋ฅผ ํตํด ๋ฏธ๋ฆฌ ์ ๋๋ก fetching ํ๊ฒ ํ๋ ค๋ฉด, Next.js์๊ฒ ํ๋ฉด์ ๋ณด์ฌ์ค url๊ณผ ๋ฏธ๋ฆฌ fetchingํ url ๋ชจ๋๋ฅผ ์ ๋ฌํด์ผ ํฉ๋๋ค.
์๋ฅผ ๋ค์ด, ์ธ์ฆ๋ ์ฌ์ฉ์์ ๋ฐฉ๋ฌธ์์ ๋์๋ณด๋ ํ๋ฉด์ ๋ถ๊ธฐ ํด์ผ ํ๋ ๊ฒฝ์ฐ ์๋์ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
// middleware.js (ํ๋ก์ ํธ ์ต์๋จ์ ์์น)
export function middleware(req) {
const nextUrl = req.nextUrl
if(nextUrl.pathname === '/dashboard') {
if(req.cookies.authToken) {
return NextResponse.rewrite(new URL('/auth/dashboard', req.url))
} else {
return NextResponse.rewrite(new URL('/public/dashboard', req.url))
}
}
}
์ด๋ฌํ ์ํฉ์ ํ์ด์ง ํ๋ฉด์์ ์ฝ๋๋ฅผ ์์ฑํ๊ฒ ๋๋ค๋ฉด,
// Page.js
import Link from 'next/link'
import useIsAuthed from './hooks/useIsAuthed'
export default function Page() {
const isAuthed = useIsAuthed()
const path = isAuthed ? '/auth/dashboard' : '/dashboard'
return (
<Link as="/dashboard" href={path}>
Dashboard
</Link>
)
}
๋์ ๋ผ์ฐํ ์ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ์๋ as ์ href props๊ฐ ํ์ํฉ๋๋ค. Dynamic Route๋ฅผ middleware๋ฅผ ์ด์ฉํด ๋ค๋ฅด๊ฒ ํ์ํ๊ณ ์ถ๋ค๋ฉด ์๋์ ๊ฐ์ด ์ฝ๋๋ฅผ ์์ฑํ ์ ์์ต๋๋ค.
<Link href={{ pathname: '[๋ชฉ์ ์ฃผ์]', query: { key: [value] } }} as='[๋
ธ์ถ๋ ์ฃผ์]'>[๋งํฌ๋ช
]</Link>
๊ทธ๋ฆฌ๊ณ ์ด๋ฅผ Next.js ๊ณต์ ๋ฌธ์์ ๋์จ ์์์ ๊ฐ์ด ํ์ธํด๋ณด๋ฉด, ์๋์ ๊ฐ์ต๋๋ค.
<Link href={{ pathname: '/dashboard/authed/[user]', query: { user: username } }} as="/dashboard/[user]">Profile</Link>
References..
https://nextjs.org/docs/app/building-your-application/routing/middleware
https://nextjs.org/docs/app/building-your-application/routing/middleware#matching-paths
'Front-end' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
Next.js 13 Paradigm (0) | 2023.09.05 |
---|---|
์ ์ ๊ท ๋ณ์๊ฐ ์๋ useState๋ฅผ ์ฌ์ฉํด์ผ ํ ๊น? (0) | 2023.02.18 |
zustand(with TypeScript) | ์ฌ์ด๋ ํ๋ก์ ํธ์์ ์ฌ์ฉํด๋ณด๊ธฐ (0) | 2023.01.17 |
๐ปzustand ์ดํดํ๊ธฐ (0) | 2023.01.16 |