Introduction
When deleting an object from a list, I expect it to immediately disappear. Or when I submit a form, I might expect to be brought back to a specific screen. All this can be achieve by redirecting and in this mini article, I will talk about some of the redirect options.
redirect
Redirect is often used after a mutation or an event. For example when creating a post or deleting one.
export const deleteProject = async (id: string) => {
// ...
redirect(projectsPath()); // Path from path.ts
};| Source |
|---|
| π Next.js Documentation > redirect |
permanentRedirect
PermanentRedirect is often use for bigger changes that will mutate an entityβs URL such as updating a userβs profile URL after they changed their username.
| Source |
|---|
| π Next.js Documentation > permanentRedirect |
Further redirects
Besides these two redirects options, there are a bunch more wich are documented in the Next.js documentation.
| Source |
|---|
| π Next.js Documentation > Redirecting |
revalidatePath
Sometimes I donβt want to be redirected, but instead I want my current Page to reload after an Action occurred. In that case I can use the revalidatepath function.
An example could be: After I edit an element, I wanna stay on the same view but with the content being updated.
// import { revalidatePath } from "next/cache";
revalidatePath(projectsPath());