ใน Next.js, คุณสามารถทำการ redirect หน้าเว็บไปยัง URL อื่นๆ ได้โดยใช้สองวิธีหลักคือ:
Client-Side Navigation: สำหรับการเปลี่ยนเส้นทางเพียงแค่เปลี่ยนหน้าโดยไม่ต้องโหลดหน้าใหม่ ใช้
next/routerเพื่อนำทางฝั่งไคลเอนต์ (client-side) ไปยัง URL ปลายทางที่คุณต้องการ.Server-Side Redirect: สำหรับการ redirect ที่ต้องการให้เซิร์ฟเวอร์ส่ง response โดยตรงให้ client ใช้
contextในgetServerSidePropsหรือgetServerSidePropsภายใต้getInitialPropsเพื่อทำการ redirect.
นี่คือวิธีการใช้ทั้งสองแบบ:
Client-Side Navigation:
ในตัวอย่างนี้เราจะใช้ next/router เพื่อนำทางไปยัง URL อื่นๆ บนฝั่งไคลเอนต์:
1 | import { useRouter } from 'next/router'; |
Server-Side Redirect:
การ redirect ที่เกิดขึ้นในฝั่งเซิร์ฟเวอร์ (server-side) สามารถทำได้โดยการใช้ context ใน getServerSideProps หรือ getServerSideProps ภายใต้ getInitialProps:
ใน getServerSideProps:
1 | export async function getServerSideProps(context) { |
หรือใน getInitialProps:
1 | class RedirectToAnotherPage extends React.Component { |
ต้องการระวังเรื่องการใช้ res.writeHead ใน Next.js เนื่องจากมันทำการออก header สำหรับ response และจบการทำงานของ request จึงต้องครอบคลุมกรณีที่คุณไม่ต้องการสิ่งนี้โดยการใช้ return null; ใน render ของคลาสหรือการคืนค่า return { props: {} }; ใน getServerSideProps เพื่อป้องกันข้อผิดพลาดที่เกิดขึ้นหากไม่ได้คืนค่าอะไรก็ตามในฟังก์ชัน getServerSideProps หรือ getInitialProps.