-
Notifications
You must be signed in to change notification settings - Fork 27k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Error: NEXT_REDIRECT while using server actions #49298
Comments
He have the same bug! This is my code if is useful: "use server"
import { CourseId } from "@/Contexts/Mooc/Shared/domain/Courses/CourseId";
import { MongoClientFactory } from "@/Contexts/Shared/infrastructure/persistence/mongo/MongoClientFactory";
import { MongoCourseRepository } from "@/Contexts/Mooc/Courses/infrastructure/persistence/MongoCourseRepository";
import { Course } from "@/Contexts/Mooc/Courses/domain/Course";
import { redirect } from "next/navigation";
import { RedirectType } from "next/dist/client/components/redirect";
export async function createCourse(form: FormData) {
try {
const data = {
id: CourseId.random().value,
name: form.get("name") as string,
duration: form.get("duration") as string,
}
const url = "mongodb://localhost:27017/next13-fullstack"
const client = MongoClientFactory.createClient("mooc", { url })
const repository = new MongoCourseRepository(client)
const course = Course.fromPrimitives(data)
await repository.save(course);
redirect("/", RedirectType.push)
} catch (error) {
let message= "Something went wrong"
console.log(error)
if (error instanceof Error) {
message = error.message
}
redirect(`/?error=${message}`, RedirectType.push)
}
} import styles from "./CourseForm.module.css";
import { createCourse } from "@/components/CourseForm/actions/createCourse";
export function CourseForm() {
return (
<form className={styles.form}>
<div className={styles.form__field}>
<label className={styles.form__label} htmlFor="name">Name</label>
<input className={styles.form__input} type="text" name="name" id="name" />
</div>
<div className={styles.form__field}>
<label className={styles.form__label} htmlFor="duration">Duration</label>
<input className={styles.form__input} type="text" name="duration" id="duration" />
</div>
<button className={styles.form__button} formAction={createCourse}>Create new course</button>
</form>
)
} |
I removed the try-catch from my code and now the redirect works, thanks |
Mine doesn't have any try catch. I don't do error handling until the main flow of a feature is complete. |
You have to place the Try to place less code in a try-catch anyway. You'll get the same behaviour of If you have a global error handler/wrapper, you can rethrow it with something like: } catch (err) {
if(isRedirectError(err)) throw err;
// ...
} This sounds like something an eslint rule should be able to handle well |
@jeengbe I'm using it inside a server action: const handleEdit = async (formData: FormData) => {
const handleEdit = async (formData: FormData) => {
"use server";
try {
await update({
id: Number(forum.id),
title: String(formData.get("title")),
content: String(formData.get("content")),
});
revalidatePath(`/admin/forums/${forum.id}`);
redirect(`/admin/forums`);
} catch (error) {
console.log(error);
}
}; As you can see above, I would like to revalidate a path and redirect to the forums list page only if the Can you please suggest a way in which I can do this without a |
You can limit the scope of your try-catch: const handleEdit = async (formData: FormData) => {
"use server";
try {
await update({
id: Number(forum.id),
title: String(formData.get("title")),
content: String(formData.get("content")),
});
} catch (error) {
console.log(error);
}
revalidatePath(`/admin/forums/${forum.id}`);
redirect(`/admin/forums`);
}; |
Won't the above |
As others have pointed out the way const handleEdit = async (formData: FormData) => {
"use server";
try {
await update({
id: Number(forum.id),
title: String(formData.get("title")),
content: String(formData.get("content")),
});
revalidatePath(`/admin/forums/${forum.id}`);
redirect(`/admin/forums`);
} catch (error) {
// you end up catching the `redirect()` above in this case.
console.log(error);
}
}; One way to fix it:
We'll make sure the docs are updated to explain |
I noticed a behaviour that's not really intuitive at first: → The Otherwise said: This works
This breaks with a
I believe this is the source for your error @JoseVSeb. Is this behaviour expected @timneutkens ? |
@benjaminwaterlot thanks, that was the issue. Although, i don't understand why that's needed. |
Assuming
The right way to go about it is this:
In the experimental version of React that is enabled when you enable server actions async transitions are supported (it's what Hope that clarifies why it would not be caught when you "just call it" instead of returning. It's similar to not awaiting any other async function |
Thanks a lot for your answer 🙂 I didn't realize an error in a dangling promise couldn't be caught, and by reflex I used this the same way the nextjs documentation uses Maybe an uncaught |
Hey folks, I'm encountering the same issue with the latest release 13.4.3 something as simple as this:
Gives me the same redirect error as the OP, what am i missing? |
Also facing the same thing -- are we not supposed to redirect inside server actions? nvm-- fixed it by returning the promise in the onStart(() => .. ) inside the button's onClick |
Dealing with this now, found a discussion that relates #50170 |
I removed try catch and works idk why but its works |
@JawadFadel because |
works great! |
I ran into the same issue and this fixes it, but it throws a type error. A transition function can only return void or undefined, and returning a Promise breaks that. |
This is actually not the case when you enable server actions. The React experimental channel has support for Async Transitions, so an async function is supported in that case. |
it still doesn't work for me, and I've tried the following:
edit: I discovered the issue I was having:
|
Can you give an example of how you do this without wrapping the server action call into try/catch? And how is this related to the |
In my project with server actions enabled I'm still getting a type error, is there an extra step required to make the React typing in sync with the experimental channel enabled by Next? |
No the issue was that I cannot use a try / catch inside of startTransition. When I removed the try / catch statement, the redirect worked. The redirect inside of the action cannot be inside of a try / catch, and the action function on the frontend cannot be inside of a try / catch either |
This closed issue has been automatically locked because it had no new activity for a month. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you. |
Verify canary release
Provide environment information
Operating System: Platform: darwin Arch: arm64 Version: Darwin Kernel Version 22.4.0: Mon Mar 6 21:01:02 PST 2023; root:xnu-8796.101.5~3/RELEASE_ARM64_T8112 Binaries: Node: 19.2.0 npm: 9.6.2 Yarn: 1.22.19 pnpm: 8.4.0 Relevant packages: next: 13.4.1-canary.2 eslint-config-next: 13.4.0 react: 18.2.0 react-dom: 18.2.0
Which area(s) of Next.js are affected? (leave empty if unsure)
App directory (appDir: true)
Link to the code that reproduces this issue
https://github.com/ghoshnirmalya/the-fullstack-app/blob/next-server-actions/src/components/admin/Forum/ForumCreateForm.tsx#L20-L68
To Reproduce
If the server actions don't use a
try...catch
block, then there is no error. The form action works as expected. However, if there is atry...catch
block, then the errorError: NEXT_REDIRECT
shows up.Note that I'm using Prisma and the data gets saved before calling
redirect(
/admin/forums/${forum.id});
. Theforum
object has the correct data.Describe the Bug
The following code works as expected:
However, if I use a
try...catch
block, then the following error showing up:The code that throws the above error is as follows:
Expected Behavior
The
redirect()
function should redirect to the correct URL instead of throwing an error.Which browser are you using? (if relevant)
Chromium Engine Version 112.0.5615.137
How are you deploying your application? (if relevant)
Vercel
The text was updated successfully, but these errors were encountered: