Toast after a server action
Wrap the server action in toast.promise: a spinner while it runs, a check when it returns ok, and your own message when it returns ok: false. Free.
Wrap the server action in toast.promise: a spinner while it runs, a check when it returns ok, and your own message when it returns ok: false. Free.
"use client";
import { toast } from "@/components/toast-stack/ToastStack";
import { saveSettings } from "./actions";
export function SaveButton({ name }: { name: string }) {
return (
<button
onClick={() =>
toast.promise(
// The action returns { ok, message }. Turn ok: false into a rejection
// here, on the client, so the error toast keeps your message.
saveSettings(name).then((r) => {
if (!r.ok) throw new Error(r.message);
return r;
}),
{
loading: { title: "Saving…" },
success: (r) => ({ title: "Saved", description: r.message }),
error: (e) => ({ title: "Couldn't save", description: e instanceof Error ? e.message : "Something went wrong" }),
},
)
}
>
Save
</button>
);
}"use server";
export type SaveResult = { ok: boolean; message: string };
export async function saveSettings(name: string): Promise<SaveResult> {
const clean = name.trim();
// Return the error instead of throwing: in production Next.js replaces
// the message of an error thrown here with a generic one.
if (!clean) return { ok: false, message: "Name can't be empty" };
// write to your database here
return { ok: true, message: `Saved ${clean}` };
}import { Toaster } from "@/components/toast-stack/ToastStack";
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
{children}
<Toaster />
</body>
</html>
);
}npx shadcn@latest add https://teodoravadani.github.io/qodesign-free/r/toast-stack.jsonAll comparisons, with prices read on each library's own site.
From the blog: Toast Notifications After a Next.js Server Action (Sonner, useActionState, redirect)
From the blog: Fix "Failed to find Server Action" in Next.js After a Deploy
Next.js hides the message of an error thrown in a server action in production builds, so the toast would show a generic error. A returned object keeps your text. Our blog post on toasts after server actions uses the same shape with useActionState.
It covers the same everyday calls (toast, success, error, promise) with a stacked deck look. Check that it has the options you use before swapping.
Yes. MIT licence.
Yes. The folder has a PROMPT.md. Paste it into Cursor, Lovable, v0 or Claude Code.
Yes, as a client component. Keep "use client" at the top of the file that renders it, as in the snippet above. App Router and Pages Router both work.