### Install and Run Example App Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Steps to set up and run the basic example application, including installing dependencies and starting the development server with a generated secret. ```sh cd examples/react/basic pnpm install START_TOAST_SECRET=$(openssl rand -hex 32) pnpm dev ``` -------------------------------- ### Install and Run Example Source: https://github.com/stevan-borus/start-toast/blob/main/examples/react/basic/README.md Use these commands to install dependencies and run the basic example locally. Open http://localhost:3000 to view the application. ```bash pnpm install pnpm --filter @tanstack-start-toast/example-basic dev # open http://localhost:3000 ``` -------------------------------- ### Install react-start-toast Source: https://context7.com/stevan-borus/start-toast/llms.txt Install the library and its peer dependencies using pnpm. ```sh pnpm add react-start-toast # peer deps: @tanstack/react-router @tanstack/react-start react react-dom ``` -------------------------------- ### Run Example App Locally Source: https://github.com/stevan-borus/start-toast/blob/main/CONTRIBUTING.md Develop and manually test the example application against the workspace-linked library. This command filters to the start-toast-example-basic package. ```sh pnpm --filter start-toast-example-basic dev ``` -------------------------------- ### Install react-start-toast Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Install the library using pnpm. It has peer dependencies on @tanstack/react-router, @tanstack/react-start, react, and react-dom. ```sh pnpm add react-start-toast ``` -------------------------------- ### Run End-to-End Tests on Example App Source: https://github.com/stevan-borus/start-toast/blob/main/CONTRIBUTING.md Execute Playwright end-to-end tests against a built version of the example application. This command filters to the start-toast-example-basic package. ```sh pnpm --filter start-toast-example-basic test:e2e ``` -------------------------------- ### Install Dependencies and Run Tests Source: https://github.com/stevan-borus/start-toast/blob/main/CONTRIBUTING.md Use these commands to set up the project and run all tests locally. Ensure your pnpm version is 10 or higher to avoid warnings. ```sh pnpm install pnpm test:ci ``` -------------------------------- ### Example Server Function with Redirect Source: https://context7.com/stevan-borus/start-toast/llms.txt An example server function demonstrating how to use `redirectWithSuccess` for redirects after an action, like signing out. It calls `auth.signOut()` before redirecting. ```typescript // src/auth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirectWithSuccess, redirectWithError } from './flash-toast-bridge.server' export const signOutFn = createServerFn({ method: 'POST' }).handler(async () => { await auth.signOut() return redirectWithSuccess('/', 'Signed out successfully') }) ``` -------------------------------- ### Verifying react-start-toast Against Specific TanStack Start Versions Source: https://github.com/stevan-borus/start-toast/blob/main/examples/react/basic/KNOWN_ISSUES.md Instructions for adding react-start-toast to a consumer application and specifying a target version of @tanstack/react-start for verification. This process helps ensure the library functions correctly with different TanStack Start environments. ```sh # In a fresh consumer app: pnpm add react-start-toast pnpm add @tanstack/react-start@ # Wire up per the lib README, then exercise a flow that goes through redirectWithSuccess. ``` -------------------------------- ### Re-export Server-Only Helpers Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Create a local file with a .server.ts extension to re-export server-only helpers. This leverages TanStack Start's import-protection plugin to externalize these imports from the client bundle. ```ts // src/flash-toast-bridge.server.ts export { consumeFlashToast, redirectWithError, redirectWithSuccess, setFlashToast, // ...whichever helpers you actually use } from 'react-start-toast/server' ``` -------------------------------- ### TanStack Start Toast Server Exports Source: https://github.com/stevan-borus/start-toast/blob/main/docs/adr/0001-roadmap.md Defines the wire format, configuration options, primitive functions, and redirect helpers for server-side toast management. This includes types for toast messages and inputs, functions to set cookie options, and utilities for setting and consuming flash toasts. ```typescript // === Wire format === export type FlashToast // {message, type, description?, duration?, _id} export type FlashToastInput // string | {message, type?, description?, duration?} export type FlashToastType // 'info' | 'success' | 'error' | 'warning' export const flashToastSchema // z.object(...) // === Configuration === export function setFlashCookieOptions(opts: FlashCookieOptions): void // === Primitives === export async function setFlashToast(input, defaultType?) export async function consumeFlashToast(): Promise export const consumeFlashToastFn // server-fn — for root-loader use // === Redirect helpers (push history) === export async function redirectWithToast(href, input) // Promise export async function redirectWithSuccess(href, input) export async function redirectWithError(href, input) export async function redirectWithInfo(href, input) export async function redirectWithWarning(href, input) // === Replace helpers (no history entry) === export async function replaceWithToast(href, input) export async function replaceWithSuccess(href, input) export async function replaceWithError(href, input) export async function replaceWithInfo(href, input) export async function replaceWithWarning(href, input) ``` -------------------------------- ### Pinning TanStack Start Versions with pnpm Overrides Source: https://github.com/stevan-borus/start-toast/blob/main/examples/react/basic/KNOWN_ISSUES.md This configuration is used in the root package.json to pin coherent versions of internal TanStack Start packages, resolving dev-mode version skew issues. This workaround is specific to the development environment and should be removed once upstream releases are coordinated. ```json { "pnpm": { "overrides": { "@tanstack/start-plugin-core": "1.167.34", "@tanstack/start-server-core": "1.167.40", "@tanstack/react-start": "1.167.40" } } } ``` -------------------------------- ### Configure ToastProvider in Root Component Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Set up the ToastProvider in your root component to manage toasts. This example integrates with sonner for toast UI and consumes flash toasts from loader data. ```tsx import { createRootRoute, Outlet, Scripts } from '@tanstack/react-router' import { ToastProvider } from 'react-start-toast' import { Toaster, toast } from 'sonner' import { consumeFlashToastFn } from '../flash-toast.functions' export const Route = createRootRoute({ loader: async () => ({ flashToast: await consumeFlashToastFn() }), component: RootComponent, }) function RootComponent() { const { flashToast } = Route.useLoaderData() return ( } toast={flashToast} notify={(t) => toast[t.type](t.message, t)} > ) } ``` -------------------------------- ### Client-side Toast Provider Integration Source: https://context7.com/stevan-borus/start-toast/llms.txt Wrap your toast UI with `` for correct source order, ensuring subscribe-on-mount UIs are ready before `notify` fires. This is the recommended client-side integration. ```tsx import { createRootRoute, Outlet } from '@tanstack/react-router' import { ToastProvider } from 'react-start-toast' import { Toaster, toast } from 'sonner' import { consumeFlashToastFn } from '../flash-toast.functions' export const Route = createRootRoute({ loader: async () => ({ flashToast: await consumeFlashToastFn(), // FlashToast | null }), component: RootComponent, }) function RootComponent() { const { flashToast } = Route.useLoaderData() return ( // ToastProvider mounts first, then , // ensuring sonner's subscriber is ready before notify() fires. } toast={flashToast} notify={(t) => toast[t.type](t.message, { description: t.description, duration: t.duration })} > ) } ``` -------------------------------- ### Generate a Changeset Source: https://github.com/stevan-borus/start-toast/blob/main/CONTRIBUTING.md Run this command to create a changeset file for documenting user-facing changes. This is required for all changes that affect published behavior. ```sh pnpm changeset ``` -------------------------------- ### Stage toast and redirect with helpers Source: https://context7.com/stevan-borus/start-toast/llms.txt Use `redirectWithSuccess`, `redirectWithError`, `redirectWithInfo`, or `redirectWithWarning` to stage a toast and immediately redirect. These helpers work in loaders, `beforeLoad`, and server fn handlers, signaling unreachable code with `Promise`. ```typescript // src/auth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirectWithSuccess, redirectWithError, redirectWithWarning, } from './flash-toast-bridge.server' export const loginFn = createServerFn({ method: 'POST', }) .inputValidator((data: { email: string; password: string }) => data) .handler(async ({ data }) => { const user = await auth.signIn(data.email, data.password) if (!user) { // String shorthand — type defaults to 'error' return redirectWithError('/login', 'Invalid credentials') } if (user.requiresMfa) { return redirectWithWarning('/mfa', 'Please complete two-factor auth') } // Object input with optional description and duration return redirectWithSuccess('/dashboard', { message: `Welcome back, ${user.name}!`, description: 'You were last seen 2 days ago.', duration: 5000, }) }) ``` -------------------------------- ### Stage Toast from Server Function (with redirect) Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Use `redirectWithSuccess` from your server bridge to stage a toast that will be displayed after a full page navigation. Ensure your server bridge is correctly imported. ```ts // src/auth.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirectWithSuccess } from './flash-toast-bridge.server' export const loginFn = createServerFn({ method: 'POST' }).handler(async () => { await myAuth.signIn(/* ... */) return redirectWithSuccess('/dashboard', 'Welcome back!') }) ``` -------------------------------- ### Root Route with ToastProvider and Loader Source: https://context7.com/stevan-borus/start-toast/llms.txt Sets up the root route for the application, including a loader that fetches flash toast data and a ToastProvider to manage and display toasts. It integrates with Sonner for the toast UI. ```tsx // src/routes/__root.tsx import { createRootRoute, Outlet } from '@tanstack/react-router' import { ToastProvider } from 'react-start-toast' import { Toaster, toast } from 'sonner' import { consumeFlashToastFn } from '../flash-toast.functions' export const Route = createRootRoute({ loader: async () => ({ flashToast: await consumeFlashToastFn() }), component: () => { const { flashToast } = Route.useLoaderData() return ( } toast={flashToast} notify={(t) => toast[t.type](t.message, { description: t.description, duration: t.duration })} > ) }, }) ``` -------------------------------- ### `redirectWithSuccess` / `redirectWithError` / `redirectWithInfo` / `redirectWithWarning` Source: https://context7.com/stevan-borus/start-toast/llms.txt Helper functions to stage a flash toast of a specific type and then immediately redirect the user. They throw a TanStack Router `redirect` to the specified URL. ```APIDOC ## `redirectWithSuccess` / `redirectWithError` / `redirectWithInfo` / `redirectWithWarning` — Stage and redirect Each helper stages a flash toast of the matching type and throws a TanStack Router `redirect` to `href`. The `Promise` return type signals unreachable code after the call. Works identically from loaders, `beforeLoad`, or server fn handlers. ### Parameters - **href** (string) - Required - The URL to redirect to. - **message** (string | FlashToastInput) - Required - The toast message or a `FlashToastInput` object. - **type** (string) - Optional - The type of the toast. Defaults to 'error' if `message` is a string and `type` is not specified. Can be 'success', 'error', 'info', 'warning'. - **description** (string) - Optional - A more detailed description for the toast (used when `message` is an object). - **duration** (number) - Optional - The duration in milliseconds the toast should be displayed (used when `message` is an object). ### Example Usage ```ts // Redirect with an error message (type defaults to 'error') return redirectWithError('/login', 'Invalid credentials') // Redirect with a warning message return redirectWithWarning('/mfa', 'Please complete two-factor auth') // Redirect with a success message using an object for detailed options return redirectWithSuccess('/dashboard', { message: `Welcome back, User!`, description: 'You were last seen 2 days ago.', duration: 5000, }) ``` ``` -------------------------------- ### Configure Cookie Secret and Options Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Set the START_TOAST_SECRET environment variable (>=32 characters). For runtime-resolved secrets, call setFlashCookieOptions once at app boot from a server-bundled file. ```ts // In e.g. src/server.ts (anywhere server-only) import { setFlashCookieOptions } from 'react-start-toast/server' setFlashCookieOptions({ name: 'my-flash', maxAge: 30, secret: () => myVault.read('flash-secret'), }) ``` -------------------------------- ### Server-Side Redirect with Success Toast Source: https://github.com/stevan-borus/start-toast/blob/main/packages/react-start-toast/README.md Use `redirectWithSuccess` in a server-fn handler to redirect the user to a new page while displaying a success toast message. Ensure the `react-start-toast/server` module is imported. ```typescript const { redirectWithSuccess } = await import( 'react-start-toast/server' ) await redirectWithSuccess('/dashboard', 'Logged in!') ``` -------------------------------- ### Run Vitest in Watch Mode Source: https://github.com/stevan-borus/start-toast/blob/main/CONTRIBUTING.md Execute the library tests in watch mode for continuous feedback during development. This command filters to the react-start-toast package. ```sh pnpm --filter react-start-toast test:lib --watch ``` -------------------------------- ### `redirectWithToast` Source: https://context7.com/stevan-borus/start-toast/llms.txt Stages a flash toast with an explicitly defined type and then redirects the user. This function is useful when the toast type is determined at runtime. ```APIDOC ## `redirectWithToast` — Stage and redirect with explicit type Like `redirectWithSuccess` etc., but accepts any `FlashToastInput` and defaults the type to `'info'` when the input is an object without a `type` field. Use this when you want to pass through a type value determined at runtime. ### Parameters - **href** (string) - Required - The URL to redirect to. - **toastInput** (FlashToastInput) - Required - An object containing the toast details (`message`, `type`, optional `description`, `duration`). ### Example Usage ```ts return redirectWithToast('/home', { message: data.message, type: 'info', // can be 'info' | 'success' | 'error' | 'warning' description: 'This is an informational notice.', duration: 4000, }) ``` ``` -------------------------------- ### Client-Side Components and Types Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Client-safe components and types for rendering and managing flash toasts. ```APIDOC ## ### Description An effect-only component that handles the rendering and deduplication of flash toasts based on `_id` in `sessionStorage`. ### Props - **toast** (FlashToast | null) - The current toast object to display, or null. - **notify** ( (t: FlashToast) => void ) - A function to trigger a new toast notification. ``` ```APIDOC ## ### Description A provider component that composes `` and `` to manage and display flash toasts within the application. ### Props - **toaster** - Represents the toaster instance. - **toast** (FlashToast | null) - The current toast object. - **notify** ( (t: FlashToast) => void ) - Function to trigger a toast notification. - **children** - The child elements to be rendered within the provider. ``` ```APIDOC ## FlashToast (Type) ### Description Defines the structure of a flash toast object. ### Fields - **message** (string) - Required - The main message of the toast. - **type** (FlashToastType) - Required - The type of the toast (e.g., 'info', 'success'). - **_id** (string) - Required - A unique identifier for the toast, used for deduplication. - **description** (string) - Optional - A more detailed description for the toast. - **duration** (number) - Optional - The duration in milliseconds the toast should be visible. ``` ```APIDOC ## FlashToastInput (Type) ### Description Defines the acceptable input formats for creating a flash toast. ### Types - **string**: A simple string representing the toast message. - **object**: An object with the following properties: - **message** (string) - Required - The main message of the toast. - **type** (FlashToastType) - Optional - The type of the toast. - **description** (string) - Optional - A detailed description for the toast. - **duration** (number) - Optional - The duration in milliseconds the toast should be visible. ``` ```APIDOC ## FlashToastType (Type) ### Description Defines the possible types for a flash toast. ### Allowed Values - `'info'` - `'success'` - `'error'` - `'warning'` ``` -------------------------------- ### Define Server Function for Root Loader Source: https://context7.com/stevan-borus/start-toast/llms.txt Create a server function using createServerFn to consume flash toasts in the root loader. This function reads and clears the toast cookie. ```typescript // src/flash-toast.functions.ts import { createServerFn } from '@tanstack/react-start' import type { FlashToast } from 'react-start-toast' import { consumeFlashToast } from './flash-toast-bridge.server' export const consumeFlashToastFn = createServerFn({ method: 'POST' }).handler( async (): Promise => consumeFlashToast(), ) // Returns the staged FlashToast ({ message, type, _id, description?, duration? }) // or null when nothing is staged. Automatically clears the cookie after reading. ``` -------------------------------- ### Configure Flash Cookie Options Source: https://context7.com/stevan-borus/start-toast/llms.txt Override default cookie settings like name, maxAge, and security flags. The secret is required if START_TOAST_SECRET is not set. ```typescript // src/server.ts (server-only, runs at app boot) import { setFlashCookieOptions } from 'react-start-toast/server' // Simple: hard-code a name and maxAge setFlashCookieOptions({ name: 'my-flash', // default: '__start_toast' maxAge: 30, // default: 60 seconds secure: true, // default: process.env.NODE_ENV === 'production' sameSite: 'strict', // default: 'lax' }) // Advanced: runtime-resolved secret (Vault, AWS Secrets Manager, etc.) setFlashCookieOptions({ secret: () => process.env.FLASH_SECRET ?? myVault.read('flash-secret'), }) // Precedence: explicit secret option > START_TOAST_SECRET env var > throws ``` -------------------------------- ### Avoid Toast Drop with Client-Side Link Navigation Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Do not use `redirectWith*` functions from a client-side `` or `useMutation` callback that triggers a client-side router transition. This can cause the toast to be silently dropped because the loader's consume-fetch races the cookie commit. ```tsx // ❌ through a redirect-throwing loader — toast silently dropped Go ``` -------------------------------- ### Define Local Server Function to Consume Toast Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Define a local server function, consumeFlashToastFn, that calls consumeFlashToast. This is the required RPC seam for the bridge to surface staged toasts in your __root.tsx loader. ```ts // src/flash-toast.functions.ts import { createServerFn } from '@tanstack/react-start' import type { FlashToast } from 'react-start-toast' import { consumeFlashToast } from './flash-toast-bridge.server' export const consumeFlashToastFn = createServerFn({ method: 'POST' }).handler( async (): Promise => consumeFlashToast(), ) ``` -------------------------------- ### Stage Toast from Server Function (without redirect) Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Stage a toast message from any server function handler without performing a redirect. This is useful for actions that complete on the same page or don't require navigation. ```ts import { setFlashToast } from './flash-toast-bridge.server' // ...inside any server fn handler: await setFlashToast({ message: 'Saved', type: 'success' }) return data ``` -------------------------------- ### TypeScript Types for Flash Toasts Source: https://context7.com/stevan-borus/start-toast/llms.txt Import `FlashToast`, `FlashToastInput`, and `FlashToastType` from `react-start-toast` for typing loader data, server function return types, and custom notification wrappers. ```typescript import type { FlashToast, FlashToastInput, FlashToastType } from 'react-start-toast' // FlashToast — the wire format returned by consumeFlashToast / consumeFlashToastFn const toast: FlashToast = { message: 'Payment received', type: 'success', // 'info' | 'success' | 'error' | 'warning' description: 'Invoice #1042 for $99.00', // optional duration: 5000, // optional, in ms _id: 'lm3k2-abc123', // auto-generated dedupe key — never set manually } // FlashToastInput — what setFlashToast and redirectWith* accept const input1: FlashToastInput = 'Profile saved' // string shorthand const input2: FlashToastInput = { message: 'Profile saved', type: 'success' } const input3: FlashToastInput = { message: 'Done', description: 'Details...', duration: 3000 } // FlashToastType const type: FlashToastType = 'warning' // 'info' | 'success' | 'error' | 'warning' ``` -------------------------------- ### Stage toast and redirect with explicit type Source: https://context7.com/stevan-borus/start-toast/llms.txt The `redirectWithToast` function allows staging a toast with any `FlashToastInput` and an explicit type. It defaults the type to 'info' if not provided in an object input. Useful for runtime-determined toast types. ```typescript // src/notifications.functions.ts import { createServerFn } from '@tanstack/react-start' import { redirectWithToast } from './flash-toast-bridge.server' export const notifyFn = createServerFn({ method: 'POST', }) .inputValidator((data: { message: string; type: string }) => data) .handler(async ({ data }) => { return redirectWithToast('/home', { message: data.message, type: 'info', // can be 'info' | 'success' | 'error' | 'warning' description: 'This is an informational notice.', duration: 4000, }) }) ``` -------------------------------- ### Correct Source Order for Toaster Components Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Ensure the toaster component mounts before the toast effect to prevent toasts from being silently dropped. This is crucial for toast UIs that buffer events arriving before subscription. ```tsx // ✅ Correct — toaster mounts first, subscribes, then the bridge fires ``` ```tsx // ❌ Wrong — bridge fires before toaster subscribes; toast is silently dropped ``` -------------------------------- ### Index Route with Sign-Out Form Source: https://context7.com/stevan-borus/start-toast/llms.txt A simple index route component that renders a form for signing out. Submitting this form triggers the `signOutFn` server function, initiating a full navigation flow that includes a flash toast. ```tsx // src/routes/index.tsx — trigger a sign-out toast via HTML form submission import { createFileRoute } from '@tanstack/react-router' import { signOutFn } from '../auth.functions' export const Route = createFileRoute('/')({ component: () => ( // ✅ Form submission = full navigation = cookie commits before the redirect target loads
{ e.preventDefault(); await signOutFn() }}>
), }) ``` -------------------------------- ### Re-export Server Helpers for Flash Toasts Source: https://context7.com/stevan-borus/start-toast/llms.txt This file re-exports server-side helpers for flash toasts, ensuring they are not included in the client bundle. Use '.server.ts' extension for these files. ```typescript // src/flash-toast-bridge.server.ts export { consumeFlashToast, redirectWithSuccess, redirectWithError, setFlashToast, } from 'react-start-toast/server' ``` -------------------------------- ### Server-Side Operations Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Server-only functions for managing flash toasts. ```APIDOC ## setFlashToast ### Description Stages a toast message to be displayed on the next request. If multiple toasts are staged, the last one written will be used. ### Method `setFlashToast(input: FlashToastInput, defaultType?: FlashToastType) => Promise` ### Parameters - **input** (FlashToastInput) - Required - The content of the toast message. - **defaultType** (FlashToastType) - Optional - The default type for the toast (e.g., 'info', 'success'). ### Notes This function stages the toast on the response cookie. ``` ```APIDOC ## consumeFlashToast ### Description Reads and clears the staged flash toast from the cookie. ### Method `consumeFlashToast() => Promise` ### Return Value - **FlashToast | null** - The staged toast object, or `null` if no toast is staged. ``` ```APIDOC ## setFlashCookieOptions ### Description Overrides the default options for the flash toast cookie. ### Method `setFlashCookieOptions(opts: FlashCookieOptions) => void` ### Parameters - **opts** (FlashCookieOptions) - Required - An object containing cookie options to override. - `name` (string) - The name of the cookie. - `maxAge` (number) - The maximum age of the cookie in seconds. - `secret` (string) - The secret key for signing the cookie. - `path` (string) - The path for the cookie. - `sameSite` ('Strict' | 'Lax' | 'None') - The SameSite attribute for the cookie. - `secure` (boolean) - Whether the cookie should only be sent over HTTPS. - `httpOnly` (boolean) - Whether the cookie should be inaccessible to client-side scripts. ``` ```APIDOC ## redirectWithToast ### Description Stages a toast message and then performs a redirect to the specified URL. ### Method `redirectWithToast(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to redirect to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes Defaults to `type: 'info'` for the toast. ``` ```APIDOC ## redirectWithSuccess ### Description Stages a success toast message and then performs a redirect to the specified URL. ### Method `redirectWithSuccess(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to redirect to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes Defaults to `type: 'success'` for the toast. ``` ```APIDOC ## redirectWithError ### Description Stages an error toast message and then performs a redirect to the specified URL. ### Method `redirectWithError(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to redirect to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes Defaults to `type: 'error'` for the toast. ``` ```APIDOC ## redirectWithInfo ### Description Stages an info toast message and then performs a redirect to the specified URL. ### Method `redirectWithInfo(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to redirect to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes Defaults to `type: 'info'` for the toast. ``` ```APIDOC ## redirectWithWarning ### Description Stages a warning toast message and then performs a redirect to the specified URL. ### Method `redirectWithWarning(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to redirect to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes Defaults to `type: 'warning'` for the toast. ``` ```APIDOC ## replaceWith* ### Description Stages a toast message and then replaces the current history entry with the new URL. This is similar to `redirectWith*` but uses `history.replaceState`. ### Method `replaceWith*(href: string, input: FlashToastInput) => Promise` ### Parameters - **href** (string) - Required - The URL to navigate to. - **input** (FlashToastInput) - Required - The content of the toast message. ### Notes There are 5 variations for different toast types: `replaceWithToast`, `replaceWithSuccess`, `replaceWithError`, `replaceWithInfo`, `replaceWithWarning`. ``` -------------------------------- ### Create .server.ts Bridge File Source: https://context7.com/stevan-borus/start-toast/llms.txt Use a .server.ts file to re-export server-only functions, preventing Node-specific code from entering the client bundle. ```typescript // src/flash-toast-bridge.server.ts export { consumeFlashToast, redirectWithError, redirectWithInfo, redirectWithSuccess, redirectWithToast, redirectWithWarning, replaceWithError, replaceWithInfo, replaceWithSuccess, replaceWithToast, replaceWithWarning, setFlashToast, } from 'react-start-toast/server' // Importing react-start-toast/server directly at the top level of a route file // crashes the production build: "node:async_hooks externalized for browser compatibility". // This .server.ts choke point fixes it categorically. ``` -------------------------------- ### `consumeFlashToast` Source: https://context7.com/stevan-borus/start-toast/llms.txt Reads and clears a staged flash toast from the cookie. It verifies the HMAC, parses the toast data, and immediately removes the cookie. Returns null if any step fails. ```APIDOC ## `consumeFlashToast` — Read and clear the staged toast Read the sealed cookie value, verify the HMAC, parse with the zod schema, and immediately clear the cookie. Returns `null` on any failure (missing cookie, wrong secret, schema mismatch). Used inside `consumeFlashToastFn`. ### Returns - **FlashToast | null** - An object containing the toast details (`message`, `type`, `_id`, optional `description`, `duration`), or `null` if no valid toast is found. ``` -------------------------------- ### Low-level FlashToastEffect Renderer Source: https://context7.com/stevan-borus/start-toast/llms.txt Use `` directly for precise control over toast placement in the tree, especially when composing multiple layout levels. Ensure `` precedes `` in the JSX source order to avoid dropped toasts. ```tsx import { createRootRoute, Outlet } from '@tanstack/react-router' import { FlashToastEffect } from 'react-start-toast' import { Toaster, toast } from 'sonner' import { consumeFlashToastFn } from '../flash-toast.functions' export const Route = createRootRoute({ loader: async () => ({ flashToast: await consumeFlashToastFn() }), component: RootComponent, }) function RootComponent() { const { flashToast } = Route.useLoaderData() return ( <> {/* ✅ MUST come before in the tree */} toast[t.type](t.message)} /> {/* ❌ Wrong order — toast silently dropped: */} ) } ``` -------------------------------- ### Server-side Navigation with Flash Toasts Source: https://context7.com/stevan-borus/start-toast/llms.txt Use `replaceWithSuccess` or `replaceWithError` for navigation that replaces the current history entry. This is useful after form mutations to prevent resubmission on back navigation. ```typescript import { createServerFn } from '@tanstack/react-start' import { replaceWithSuccess, replaceWithError } from './flash-toast-bridge.server' export const updateProfileFn = createServerFn({ method: 'POST' }) .inputValidator((data: { bio: string }) => data) .handler(async ({ data }) => { try { await db.users.updateBio(data.bio) // replace: true means "back" from /profile won't re-show the edit form return replaceWithSuccess('/profile', 'Profile updated') } catch { return replaceWithError('/profile/edit', 'Failed to save profile') } }) ``` -------------------------------- ### `setFlashToast` Source: https://context7.com/stevan-borus/start-toast/llms.txt Stages a toast notification to be displayed on the next page navigation without causing a redirect. The toast is stored in a cookie. ```APIDOC ## `setFlashToast` — Stage a toast without redirecting Call `setFlashToast` from any server fn handler when you want to stage a notification and then return data (rather than redirecting). The cookie is written on the response; the next full-page navigation delivers the toast. ### Usage ```ts // Stage a success toast on the response cookie, then return data normally. await setFlashToast({ message: 'Settings saved', type: 'success' }) // Short-form: setFlashToast('Settings saved', 'success') // With optional fields: setFlashToast({ message: 'Saved', type: 'success', description: 'Theme updated', duration: 3000 }) ``` ### Parameters - **message** (string) - Required - The main message of the toast. - **type** (string) - Optional - The type of the toast (e.g., 'success', 'error', 'info', 'warning'). Defaults to 'info' if not provided and message is a string. - **description** (string) - Optional - A more detailed description for the toast. - **duration** (number) - Optional - The duration in milliseconds the toast should be displayed. ``` -------------------------------- ### Trigger Toast Directly in Client Mutation Success Source: https://github.com/stevan-borus/start-toast/blob/main/README.md For client-side actions initiated by mutations, directly call the toast notification function (e.g., `toast.success`) within the `onSuccess` callback. This bypasses the cookie bridge as no full page navigation is involved. ```ts // ✅ Client mutation — fire your toast UI directly, no cookie bridge const mutation = useMutation({ mutationFn: () => loginFn({ data }), onSuccess: () => toast.success('Welcome back!'), }) ``` -------------------------------- ### Trigger Toast via HTML Form Submission Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Use a standard HTML form submission for actions like login or settings saves. This triggers a full page navigation, allowing the flash toast cookie bridge to work correctly. ```html
...
``` -------------------------------- ### Dynamic Import in Server Function Handler Source: https://github.com/stevan-borus/start-toast/blob/main/README.md Use dynamic import within a server function handler as an alternative to `.server.ts` re-exports if custom build configurations restrict file naming. This ensures the import is part of the dead code removed by the transform. ```typescript .handler(async () => { const { consumeFlashToast } = await import('react-start-toast/server') return consumeFlashToast() }) ``` -------------------------------- ### Stage a toast without redirecting Source: https://context7.com/stevan-borus/start-toast/llms.txt Use `setFlashToast` to stage a notification in a server function handler without causing a redirect. The toast is stored in a cookie and delivered on the next full-page navigation. It supports message, type, description, and duration. ```typescript // src/settings.functions.ts import { createServerFn } from '@tanstack/react-start' import { setFlashToast } from './flash-toast-bridge.server' export const saveSettingsFn = createServerFn({ method: 'POST', }) .inputValidator((data: { theme: string }) => data) .handler(async ({ data }) => { await db.settings.update({ theme: data.theme }) // Stage a success toast on the response cookie, then return data normally. await setFlashToast({ message: 'Settings saved', type: 'success' }) return { ok: true } // Short-form: setFlashToast('Settings saved', 'success') // With optional fields: // setFlashToast({ message: 'Saved', type: 'success', description: 'Theme updated', duration: 3000 }) }) ``` -------------------------------- ### Read and clear staged toast Source: https://context7.com/stevan-borus/start-toast/llms.txt Call `consumeFlashToast` to read and clear a staged toast from cookies. It verifies the HMAC and parses the toast data. Returns `null` if the cookie is missing, verification fails, or parsing errors occur. ```typescript // src/flash-toast.functions.ts import { createServerFn } from '@tanstack/react-start' import type { FlashToast } from 'react-start-toast' import { consumeFlashToast } from './flash-toast-bridge.server' export const consumeFlashToastFn = createServerFn({ method: 'POST', }).handler( async (): Promise => { const toast = await consumeFlashToast() // toast is null → no cookie or verification failed // toast is { message: 'Saved', type: 'success', _id: 'lm3k2-abc123', description?: ..., duration?: ... } return toast }, ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.