Redirect inside nested server action #51040
Replies: 2 comments 2 replies
-
|
When you import the
In order to resolve this, either declare the corresponding page as Client Component by declaring Use as Client Component// page.tsx
'use client'
import { redirectToGoogle } from './action'
export default function Home() {
async function redirectWrapper() {
redirectToGoogle()
}
return (
<div className='flex min-h-screen flex-col items-center justify-between p-24'>
<h1>Welcome!</h1>
<form action={redirectWrapper}>
<button type='submit'>Redirect me to Google</button>
</form>
</div>
)
}Use as Server Component// page.tsx
import { redirect } from "next/navigation";
export default async function Home() {
async function redirectWrapper() {
"use server";
redirect("https://google.com");
}
return (
<div className="flex min-h-screen flex-col items-center justify-between p-24">
<h1>Welcome!</h1>
<form action={redirectWrapper}>
<button type="submit">Redirect me to Google</button>
</form>
</div>
);
}Reference |
Beta Was this translation helpful? Give feedback.
-
|
I might have found the simple solution! Simply await the function that has the redirect. At least that worked for me (and my function with the redirect had some async code). So instead of: // page.tsx
import { redirect } from "next/navigation";
import { redirectToGoogle } from "./action";
export default async function Home() {
async function redirectWrapper() {
"use server";
//redirect("https://google.com");
redirectToGoogle();
}
return (
<div className="flex min-h-screen flex-col items-center justify-between p-24">
<h1>Welcome!</h1>
<form action={redirectWrapper}>
<button type="submit">Redirect me to Google</button>
</form>
</div>
);
}Try: // page.tsx
import { redirect } from "next/navigation";
import { redirectToGoogle } from "./action";
export default async function Home() {
async function redirectWrapper() {
"use server";
//redirect("https://google.com");
await redirectToGoogle(); // Simply add await
}
return (
<div className="flex min-h-screen flex-col items-center justify-between p-24">
<h1>Welcome!</h1>
<form action={redirectWrapper}>
<button type="submit">Redirect me to Google</button>
</form>
</div>
);
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Hello,
I want to redirect to an external link through a server action, and I have found that if I do it when the function that I'm passing to the form is created in the same file it works, but if I do it from a nested server action that was created in a different file, it fails.
Basically, considering this server action file:
This will work and I'll be redirected to Google:
This will fail, and no redirect will happen:
Does anybody know why? I can work around this by redirecting from the server action defined in the component rather than in the one in the file, but I'm curious what's the reason behind it.
Beta Was this translation helpful? Give feedback.
All reactions