Skip to content
All components
Feedback

Sonner

Show brief, non-blocking notifications about actions and background work, with an optional undo or follow-up action.

Toasts styled with the design tokens in both schemes.

Installation

tdpxl is not an npm dependency of your app. The @tdpxl/cli command (not published to npm yet) copies the source into your project, with the registry items and npm packages it imports.

npx @tdpxl/cli add sonner

Then import it from @/components/ui/sonner. New project? Start with the installation guide.

Examples

Each example is one branch of the official demo, rendered in its own frame. The code is that branch as you would write it, with imports pointing at the default install paths.

Basic

Trigger default, success and error toasts from buttons. Showing a toast does not move focus away from the button.

"use client"

import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { Toaster } from "@/components/ui/sonner"

export function SonnerBasic() {
  return (
    <div className="flex flex-col items-start gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <Toaster />
        <Button
          emphasis="stroke"
          onClick={() => toast("Registry rebuilt", { description: "57 items written." })}
        >
          Show a toast
        </Button>
        <Button
          intent="neutral"
          emphasis="stroke"
          onClick={() => toast.success("Tokens in sync")}
        >
          Success
        </Button>
        <Button
          intent="error"
          emphasis="stroke"
          onClick={() => toast.error("Build failed")}
        >
          Error
        </Button>
      </div>
    </div>
  )
}

With undo

Confirm a reversible action with an Undo action in the toast. The example uses a scoped Toaster id; an app renders one Toaster.

"use client"

import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { Toaster } from "@/components/ui/sonner"

// Each focused example owns a scoped Toaster (unique id) so its toasts never
// render twice when all examples are shown together. An app renders one Toaster.
const UNDO_TOASTER = "sonner-demo-undo"

export function SonnerWithUndo() {
  return (
    <div className="flex flex-col items-start gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <Toaster id={UNDO_TOASTER} containerAriaLabel="Undo notifications" />
        <Button
          intent="neutral"
          emphasis="stroke"
          onClick={() =>
            toast("Conversation archived", {
              toasterId: UNDO_TOASTER,
              description: "It stays in Archive until you restore it.",
              action: {
                label: "Undo",
                onClick: () => toast("Conversation restored", { toasterId: UNDO_TOASTER }),
              },
            })
          }
        >
          Archive conversation
        </Button>
      </div>
    </div>
  )
}

Promise states

Show loading, success and error states for one asynchronous task. toast.promise updates the same toast instead of stacking new ones.

"use client"

import { toast } from "sonner"

import { Button } from "@/components/ui/button"
import { Toaster } from "@/components/ui/sonner"

const PROMISE_TOASTER = "sonner-demo-promise"

function exportReport() {
  return new Promise<{ rows: number }>((resolve) => {
    setTimeout(() => resolve({ rows: 1284 }), 2000)
  })
}

export function SonnerPromiseStates() {
  return (
    <div className="flex flex-col items-start gap-4">
      <div className="flex flex-wrap items-center gap-2">
        <Toaster id={PROMISE_TOASTER} containerAriaLabel="Export notifications" />
        <Button
          intent="neutral"
          emphasis="stroke"
          onClick={() =>
            toast.promise(exportReport(), {
              toasterId: PROMISE_TOASTER,
              loading: "Exporting report",
              success: (result) => `Report exported, ${result.rows} rows`,
              error: "Export failed. Try again from Reports.",
            })
          }
        >
          Export report
        </Button>
      </div>
    </div>
  )
}

API reference

Generated from the component's TypeScript signatures. Inherited DOM and primitive props are listed separately.

Toaster

Toasts are styled with the design tokens rather than Sonner's defaults, so a notification looks like the rest of the system in both schemes. An explicit theme prop wins; otherwise the next-themes theme is used when a ThemeProvider exists, falling back to "system".

No props of its own.

Inherited props (21)
Toaster inherited props
PropTypeDefaultDescription
idstring | undefined—Stable DOM identifier used by labels, descriptions or other explicit associations.
invertboolean | undefined—Invert the notification's color treatment using Sonner's supported styling behavior.
theme"light" | "dark" | "system" | undefined—Notification theme: light, dark or system. TDPXL's Toaster uses the surrounding theme unless overridden.
position("top-left" | "top-right" | "bottom-left" | "bottom-right" | "top-center" | "bottom-center") | undefined—Viewport position of the notification region, using the supported corner or center placements.
hotkeystring[] | undefined—Key combination used to focus the notification region.
richColorsboolean | undefined—Enable Sonner's richer status-color treatment; verify the actual rendered contrast with TDPXL's token styles.
expandboolean | undefined—Keep stacked notifications expanded instead of collapsing their presentation.
durationnumber | undefined—Default notification visibility duration in milliseconds, according to Sonner's lifecycle rules.
gapnumber | undefined—Spacing between notification items.
visibleToastsnumber | undefined—Maximum number of notifications visible in the stack at once.
closeButtonboolean | undefined—Render a notification dismissal control.
toastOptionsToastOptions | undefined—Default options passed to Sonner notifications. Caller-supplied options can override TDPXL's provided defaults.
classNamestring | undefined—Additional classes for this part. Preserve contrast, visible focus and responsive content when adapting styles.
styleimport("@types/react").CSSProperties | undefined—Inline styles for the rendered part. Preserve theme contrast, visible focus and responsive behavior.
offset(string | number | { top?: string | number; right?: string | number; bottom?: string | number; left?: string | number; }) | undefined—Notification region offset from viewport edges.
mobileOffset(string | number | { top?: string | number; right?: string | number; bottom?: string | number; left?: string | number; }) | undefined—Notification region offset used on smaller viewports.
dir"auto" | "ltr" | "rtl" | undefined—Reading direction used by the primitive. Keep it consistent with the surrounding content and Direction provider.
swipeDirections("top" | "right" | "bottom" | "left")[] | undefined—Directions in which Sonner allows notifications to be dismissed by swiping.
iconsToastIcons | undefined—Replacement icon components for supported notification states.
customAriaLabelstring | undefined—Custom accessible label used by Sonner's notification interface.
containerAriaLabelstring | undefined—Accessible name for the notification container.

Accessibility & usage

From registry/ui/sonner.meta.json (authored guidance; human review may still be pending). Behavior is checked by Storybook tests, not certified here.

When to use

  • Confirming that an action completed: 'Changes saved', 'Invite sent'.
  • Offering a short-lived Undo after a reversible action such as archive or move.
  • Reporting the outcome of background work started by the user, using toast.promise for loading, success and error.
  • Pass theme explicitly when the app does not use a next-themes ThemeProvider; customize toastOptions.classNames knowing they are merged with the token defaults, not replacing them.

When not to use

  • Errors that block the user or need attention to recover; show them in place with an alert.
  • Field validation, required instructions or anything people must read to continue.
  • Decisions that need confirmation before an action runs; use an alert dialog.
  • Notifications that must persist, such as an activity feed.

Anatomy

Toaster
TDPXL wrapper around Sonner's Toaster. Render once near the app root. Applies token classes, merges consumer toastOptions.classNames, and takes the theme from the theme prop or next-themes.
toast()
Function imported from sonner that shows a notification. Variants: toast.success, toast.error, toast.warning, toast.info, toast.loading, toast.promise and toast.dismiss.
Toast
One notification: title, optional description, optional action and cancel buttons, and an optional close button (closeButton).

Keyboard & interaction

  • Showing a toast never moves focus; the toast region is an aria-live="polite" landmark, so screen readers announce it without interrupting.
  • Alt+T (the default hotkey) moves focus to the toast region; Tab reaches action, cancel and close buttons, and Escape collapses the stack.
  • Toasts close after 4 seconds by default; the timer pauses while the stack is hovered or focused and while the page is hidden.
  • On touch, a toast can be swiped away; action buttons respond to tap, Enter and Space.
  • The action's onClick runs your code; dismissing or timing out does not run it.

Responsive behavior

  • On viewports up to 600 CSS pixels wide, Sonner stretches toasts to the screen width with side offsets; use mobileOffset to keep them clear of bottom navigation or the on-screen keyboard.
  • Up to three toasts are visible at once by default (visibleToasts); older ones collapse behind.
  • Pick a position (position prop) that does not cover primary actions or the focused field, so the toast never obscures what has focus (WCAG 2.4.11).
  • Toasts respect prefers-reduced-motion; their enter and exit animations are reduced.

Content guidelines

  • Title in a few words with the outcome: 'Report exported', not 'Success!'.
  • Optional description with one useful detail; no paragraphs.
  • At most one action, labeled with a verb ('Undo', 'View'); people must be able to complete the same task elsewhere.
  • Error toasts say what failed and where to retry: 'Export failed. Try again from Reports.'
  • Give enough time to read: increase duration for longer text or toasts with actions, so timing does not exclude slower readers (WCAG 2.2.1).

Alternatives

  • Alert — Persistent, in-place feedback that stays until resolved.
  • Alert dialog — A decision that must be made before continuing.
  • Progress — Ongoing work whose completion is measurable and should stay visible.

Resources