Server action to subscribe a user to a newsletter with validation and double opt‑in.
// Source: https://github.com/yournextstore/yournextstore | License: MIT | Copyright 2024 Your Next Store, Inc
// Provided via justclaw.it.com; keep this notice with the code.
"use server";
import { try_ } from "safe-try";
import { commerce } from "@/lib/commerce";
import { getStoreConfig } from "@/lib/store-config";
type NewsletterState = {
success: boolean;
message: string;
/** Echoed on success for lib/track.tsx. */
email?: string;
error?: string;
} | null;
export async function subscribeToNewsletter(
_prev: NewsletterState,
formData: FormData,
): Promise<NewsletterState> {
const email = formData.get("email");
if (!email || typeof email !== "string") {
return { success: false, message: "", error: "Please enter a valid email address." };
}
// The form disables its submi
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key