In this article, you will learn how redirect in next.js works under the hood by looking at the Next.js source code around redirect functionality.
My approach:
- Start from the `import { redirect } from "next/navigation"'
- Back trace the redirect function to redirect.ts file
- redirect.ts explained
- How does throwing an error make the redirect work?
- Check redirect.test.ts to understand the full context
- redirect-boundary.ts has the redirect functionality
.
But where do I find the next/navigation code? You can find this code in that is has 272 lines of code at the time of writing this article, what we are interested in is the export of “redirect” at the end of the file as shown below. Focus on what you are looking for, don’t let the other code distract you.
, you will find that redirect function is, in fact, from redirect.ts.
Let’s look at the code snippet that throws the error inside
4. How does throwing an error make the redirect work?
Redirect function throws an error that sets the error.digest, but it was not obvious as to how throwing an error makes the redirect work.
I searched long and hard, my initial thoughts were around trying to find that catch block since redirect throws an error. I scoured the server related files but of no use.
I kept at it until it started to make sense when I looked at redirect.test.ts
5. Check redirect.test.ts to understand the full context
It is evident from the test code that getURLFromRedirectError(err) is called. You will find this function
6. redirect-boundary.ts has the redirect functionality
The answer is Next.js redirect uses useRouter hook and depending on redirect type, it either pushes or replaces the url
when the error is thrown from redirect, it is caught by the redirect-boundary and redirect occurs. It is quite fascinating to find that redirect function itself does not do the redirect but rather redirect-boundary inside app-router handles the routing logic.
Conclusion:
I do not know why this API is designed this way but we could use this pattern of throwing an error from your npm package and use a boundary , preferably at the root level, to catch that error and do your thing.
If it wasn’t for me checking the redirect.test.ts code I would not have been able to figure out how the redirect works because I was hoping to find some sort out catch block in the redirect.ts but that is not the case.
Feel free to reach out to me at
SOCIAL SHARE CARD GENERATOR