---
title: Toast for Astro
description: "Astro notifications with status icons, actions, and promise states."
seo:
    title: Toast for Astro | Shadcn & Tailwind CSS
related:
    - /components/alert
    - /components/dialog
    - /components/button
sidebar:
    label: "Toast"
---

```astro
---
import { Button } from "@/components/ui/button"
import { Toast } from "@/components/ui/toast"
---

<div data-toast-notifications class="flex flex-wrap justify-center gap-2">
  <Button variant="outline" data-toast-type="default">
    Show notification
  </Button>
  <Button variant="outline" data-toast-type="success">
    Success
  </Button>
  <Button variant="outline" data-toast-type="error">
    Error
  </Button>
  <Button variant="outline" data-toast-type="info">
    Info
  </Button>
  <Button variant="outline" data-toast-type="warning">
    Warning
  </Button>
  <Toast />
</div>

<script>
  import { createToast, type ToastShowOptions } from "@data-slot/toast"

  const messages: Record<string, ToastShowOptions> = {
    default: {
      title: "Report is ready",
      description: "Your weekly activity report is available.",
    },
    success: {
      title: "Changes saved",
      description: "Your project settings are up to date.",
      type: "success",
    },
    error: {
      title: "Could not save changes",
      description: "Check your connection and try again.",
      type: "error",
    },
    info: {
      title: "Update available",
      description: "Refresh the page when you are ready.",
      type: "info",
    },
    warning: {
      title: "Storage is almost full",
      description: "Remove unused files to make room.",
      type: "warning",
    },
  }
  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-toast-notifications] [data-toast-type]",
    )
    const root = button
      ?.closest("[data-toast-notifications]")
      ?.querySelector('[data-slot="toast"]')
    const message = button && messages[button.dataset.toastType!]
    if (root && message) createToast(root).show(message)
  })
</script>
```

## Installation

### Command

```sh
bunx --bun shadcn@latest add @gnostic/toast
```

### Manual

Complete the [Installation guide](/docs/installation) first. Then copy the component files below.

Install the component packages:

```sh
bun add @data-slot/toast
```

#### src/components/ui/toast/index.ts

```ts
export { default as Toast } from './toast.astro'
export { default as ToastAction } from './toast-action.astro'
export { default as ToastClose } from './toast-close.astro'
export { default as ToastContent } from './toast-content.astro'
export { default as ToastDescription } from './toast-description.astro'
export { default as ToastIcon } from './toast-icon.astro'
export { default as ToastItem } from './toast-item.astro'
export { default as ToastTemplate } from './toast-template.astro'
export { default as ToastTitle } from './toast-title.astro'
export { default as ToastViewport } from './toast-viewport.astro'

export type { ToastProps } from './types.ts'
```

#### src/components/ui/toast/toast-action.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"
import { buttonVariants } from "../button/button-variants.ts"

type Props = HTMLAttributes<"button">
const { class: className, type = "button", ...props } = Astro.props
---

<button
  data-slot="toast-action"
  type={type}
  class={cn("shrink-0", buttonVariants({ size: "xs" }), className)}
  {...props}
>
  <slot />
</button>
```

#### src/components/ui/toast/toast-close.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import XIcon from "@lucide/astro/icons/x"
import { cn } from "cn"

type Props = HTMLAttributes<"button">
const {
  class: className,
  type = "button",
  "aria-label": label = "Close notification",
  ...props
} = Astro.props
---

<button
  data-slot="toast-close"
  type={type}
  aria-label={label}
  class={cn("inline-flex size-7 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:ring-[3px] focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4", className)}
  {...props}
>
  <slot>
    <XIcon aria-hidden="true" />
  </slot>
</button>
```

#### src/components/ui/toast/toast-content.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="toast-content"
  class={cn("flex min-w-0 flex-1 flex-col gap-0.5 overflow-hidden", className)}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/toast/toast-description.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="toast-description"
  class={cn("text-muted-foreground wrap-anywhere", className)}
  {...props}
>
  <slot />
</div>
```

#### src/components/ui/toast/toast-icon.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import CircleAlertIcon from "@lucide/astro/icons/circle-exclamation-point"
import CircleCheckIcon from "@lucide/astro/icons/circle-check"
import InfoIcon from "@lucide/astro/icons/info"
import LoaderCircleIcon from "@lucide/astro/icons/loader-circle"
import TriangleAlertIcon from "@lucide/astro/icons/triangle-exclamation-point"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div
  data-slot="toast-icon"
  aria-hidden="true"
  class={cn("shrink-0 self-center group-has-[[data-slot=toast-description]:not([hidden])]/toast:self-start group-data-[type=default]/toast:hidden [&_svg]:pointer-events-none [&_svg]:hidden [&_svg]:h-lh [&_svg]:w-4 group-data-[type=success]/toast:text-success group-data-[type=error]/toast:text-destructive group-data-[type=info]/toast:text-info group-data-[type=warning]/toast:text-warning group-data-[type=loading]/toast:opacity-80 group-data-[type=success]/toast:[&>[data-toast-icon=success]]:block group-data-[type=error]/toast:[&>[data-toast-icon=error]]:block group-data-[type=info]/toast:[&>[data-toast-icon=info]]:block group-data-[type=warning]/toast:[&>[data-toast-icon=warning]]:block group-data-[type=loading]/toast:[&>[data-toast-icon=loading]]:block group-data-[type=loading]/toast:[&>[data-toast-icon=loading]]:animate-spin motion-reduce:[&_svg]:animate-none", className)}
  {...props}
>
  <slot>
    <CircleCheckIcon data-toast-icon="success" />
    <CircleAlertIcon data-toast-icon="error" />
    <InfoIcon data-toast-icon="info" />
    <TriangleAlertIcon data-toast-icon="warning" />
    <LoaderCircleIcon data-toast-icon="loading" />
  </slot>
</div>
```

#### src/components/ui/toast/toast-item.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"li">
const { class: className, ...props } = Astro.props
---

<li
  data-slot="toast-item"
  role="status"
  aria-atomic="true"
  class={cn("rounded-lg pointer-events-auto absolute inset-x-0 bottom-0 flex w-full touch-none items-center gap-2 border bg-popover px-3.5 py-3 text-sm text-popover-foreground opacity-0 shadow-lg/5 outline-none select-none origin-bottom not-dark:bg-clip-padding before:pointer-events-none before:absolute before:inset-0 before:rounded-[inherit] before:shadow-[0_1px_--theme(--color-black/4%)] dark:before:shadow-[0_-1px_--theme(--color-white/6%)] group-data-[position*=top]/toast-viewport:top-0 group-data-[position*=top]/toast-viewport:bottom-auto group-data-[position*=top]/toast-viewport:origin-top [--toast-base-y:0px] [--toast-scale:1] [--toast-x:var(--toast-swipe-amount-x,0px)] [--toast-y:calc(var(--toast-lift,-1)*-100%)] transform-[translate3d(var(--toast-x),var(--toast-y),0)_scale(var(--toast-scale))] [transition:transform_.32s_cubic-bezier(.22,1,.36,1),opacity_.32s,height_.15s] data-[mounted=true]:[--toast-y:calc(var(--toast-base-y)+var(--toast-swipe-amount-y,0px))] [&[data-mounted=true][data-visible=true]:not([data-removed=true])]:opacity-100 [&[data-front=false][data-expanded=false]]:[--toast-base-y:calc(var(--toast-collapsed-offset-y,0px)*var(--toast-lift,-1))] [&[data-front=false][data-expanded=false]]:[--toast-scale:calc(max(0,1-var(--toast-index,0)*.05))] [&[data-front=false][data-expanded=false]]:h-(--toast-front-height) data-[expanded=true]:[--toast-base-y:calc(var(--toast-offset,0px)*var(--toast-lift,-1))] data-[expanded=true]:h-(--toast-initial-height) [&[data-front=false][data-expanded=false]]:*:opacity-0 [&[data-front=false][data-expanded=false]]:*:pointer-events-none data-[visible=false]:pointer-events-none data-[removed=true]:[--toast-y:calc(var(--toast-base-y)+var(--toast-lift,-1)*-100%)] [&[data-removed=true][data-swipe-out=true]]:[--toast-x:var(--toast-swipe-end-x,0px)] [&[data-removed=true][data-swipe-out=true]]:[--toast-y:calc(var(--toast-base-y)+var(--toast-swipe-end-y,0px))] data-[swiping=true]:transition-none after:absolute after:left-0 after:bottom-full after:h-[calc(var(--toast-gap)+1px)] after:w-full group-data-[position*=top]/toast-viewport:after:top-full group-data-[position*=top]/toast-viewport:after:bottom-auto motion-reduce:transition-none group/toast", className)}
  {...props}
>
  <slot />
</li>
```

#### src/components/ui/toast/toast-template.astro

```astro
---
import { cn } from "cn"

import ToastAction from "./toast-action.astro"
import ToastClose from "./toast-close.astro"
import ToastContent from "./toast-content.astro"
import ToastDescription from "./toast-description.astro"
import ToastIcon from "./toast-icon.astro"
import ToastItem from "./toast-item.astro"
import ToastTitle from "./toast-title.astro"

type Props = astroHTML.JSX.HTMLAttributes
const { class: className, ...props } = Astro.props
---

<template data-slot="toast-template" class={cn(className)} {...props}>
  <slot>
    <ToastItem>
      <ToastIcon />
      <ToastContent>
        <ToastTitle />
        <ToastDescription />
      </ToastContent>
      <ToastAction />
      <ToastClose />
    </ToastItem>
  </slot>
</template>
```

#### src/components/ui/toast/toast-title.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"div">
const { class: className, ...props } = Astro.props
---

<div data-slot="toast-title" class={cn("font-medium wrap-anywhere", className)} {...props}>
  <slot />
</div>
```

#### src/components/ui/toast/toast-viewport.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

type Props = HTMLAttributes<"ol">
const {
  class: className,
  "aria-label": label = "Notifications",
  ...props
} = Astro.props
---

<ol
  data-slot="toast-viewport"
  role="region"
  aria-label={label}
  class={cn("pointer-events-none fixed z-60 m-0 h-[var(--toast-stack-size,0px)] w-[calc(100%-var(--toast-inset)*2)] max-w-90 list-none p-0 font-sans [--toast-inset:--spacing(4)] [--toast-gap:12px] [--toast-collapsed-peek:12px] sm:[--toast-inset:--spacing(8)] data-[position*=top]:top-(--toast-inset) data-[position*=bottom]:bottom-(--toast-inset) data-[position*=left]:left-(--toast-inset) data-[position*=right]:right-(--toast-inset) data-[position*=center]:left-1/2 data-[position*=center]:-translate-x-1/2 group/toast-viewport", className)}
  {...props}
>
  <slot />
</ol>
```

#### src/components/ui/toast/toast.astro

```astro
---
import type { HTMLAttributes } from "astro/types"
import { cn } from "cn"

import ToastTemplate from "./toast-template.astro"
import ToastViewport from "./toast-viewport.astro"
import type { ToastProps } from "./types.ts"

type Props = HTMLAttributes<"div"> & ToastProps

const {
  class: className,
  position = "bottom-right",
  limit = 3,
  duration = 5000,
  pauseOnHover = true,
  pauseOnFocus = true,
  portal = true,
  ...props
} = Astro.props
---

<div
  data-slot="toast"
  data-position={position}
  data-limit={limit}
  data-duration={duration}
  data-pause-on-hover={String(pauseOnHover)}
  data-pause-on-focus={String(pauseOnFocus)}
  data-portal={String(portal)}
  class={cn(className)}
  {...props}
>
  <slot>
    <ToastTemplate />
    <ToastViewport />
  </slot>
</div>

<script>
  import { createToast, type ToastController } from "@data-slot/toast"

  const controllers = new Map<Element, ToastController>()
  const init = () => {
    for (const [root, controller] of controllers) {
      if (!root.isConnected) {
        controller.destroy()
        controllers.delete(root)
      }
    }
    document.querySelectorAll('[data-slot="toast"]').forEach((root) => {
      if (!controllers.has(root)) controllers.set(root, createToast(root))
    })
  }

  init()
  document.addEventListener("astro:page-load", init)
  document.addEventListener("astro:before-swap", () => {
    for (const controller of controllers.values()) controller.destroy()
    controllers.clear()
  })
</script>
```

#### src/components/ui/toast/types.ts

```ts
import type { ToastPosition } from '@data-slot/toast'
import type {
    ToastShowOptions as ToastShowOptionsType,
    ToastAction as ToastActionType,
    ToastUpdateOptions as ToastUpdateOptionsType,
    ToastPromiseOptions as ToastPromiseOptionsType,
    ToastOptions as ToastOptionsType,
} from '@data-slot/toast'

export type ToastAction = ToastActionType
export type ToastUpdateOptions = ToastUpdateOptionsType
export type ToastPromiseOptions<T> = ToastPromiseOptionsType<T>
export type ToastOptions = ToastOptionsType
export type ToastShowOptions = ToastShowOptionsType

/** Options for a notification stack. */
export interface ToastProps {
    /**
     * Position of the stack in the page viewport.
     * @default "bottom-right"
     */
    position?: ToastPosition
    /**
     * Maximum number of visible notifications.
     * @default 3
     */
    limit?: number
    /**
     * Time before dismissal, in milliseconds. Use 0 to keep a toast open.
     * @default 5000
     */
    duration?: number
    /**
     * Pause dismissal while the pointer is over the stack.
     * @default true
     */
    pauseOnHover?: boolean
    /**
     * Pause dismissal while focus is inside the stack.
     * @default true
     */
    pauseOnFocus?: boolean
    /**
     * Move the viewport to document.body to escape clipping containers.
     * @default true
     */
    portal?: boolean
}
```

Component classes use the preset configured during project setup. Select the same preset in the docs before copying Manual source. To change installed component classes, edit or reinstall their source. See [Theming](/docs/theming) for details.


## Usage

Place one `Toast` in your layout. It supplies the template, status icons, close button, and notification viewport. Its script initializes the data-slot controller.

```astro
---
import { Toast } from "@/components/ui/toast"
---

<Toast data-app-toast />

<script>
  import { createToast } from "@data-slot/toast"

  const root = document.querySelector("[data-app-toast]")!
  const toaster = createToast(root)
  toaster.show({
    title: "Changes saved",
    description: "Your project settings are up to date.",
    type: "success",
  })
</script>
```

Call `show()` from your application event handler after the root is in the document. `createToast(root)` returns the existing controller when the root is already initialized. Each root has an independent stack. With Astro navigation, find the current root before you use the controller; the component destroys its old controllers before a page swap.

## Examples

### With an action

An action dismisses its toast after the callback runs. Call `event.preventDefault()` in the callback to keep it open.

```astro
---
import { Button } from "@/components/ui/button"
import { Toast } from "@/components/ui/toast"
---

<div data-toast-undo-demo>
  <Button variant="outline" data-toast-archive>
    Archive report
  </Button>
  <Toast duration={8000} />
</div>

<script>
  import { createToast } from "@data-slot/toast"

  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest("[data-toast-archive]")
    const root = button
      ?.closest("[data-toast-undo-demo]")
      ?.querySelector('[data-slot="toast"]')
    if (!root) return
    const toaster = createToast(root)
    toaster.show({
      title: "Report archived",
      description: "You can restore it with Undo.",
      action: {
        label: "Undo",
        value: "restore-report",
        onClick: () => {
          toaster.show({
            title: "Report restored",
            description: "Successfully restored the report.",
            type: "success",
          })
        },
      },
    })
  })
</script>
```

### Promise states

Use `promise()` to change one notification from loading to success or error. The examples simulate a request. Call the returned handle's `unwrap()` when your application also needs the result or error.

```astro
---
import { Button } from "@/components/ui/button"
import { Toast } from "@/components/ui/toast"
---

<div data-toast-promise-demo class="flex flex-wrap justify-center gap-2">
  <Button variant="outline" data-toast-promise="success">
    Run success demo
  </Button>
  <Button variant="outline" data-toast-promise="error">
    Run error demo
  </Button>
  <Toast />
</div>

<script>
  import { createToast } from "@data-slot/toast"

  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-toast-promise]",
    )
    const root = button
      ?.closest("[data-toast-promise-demo]")
      ?.querySelector('[data-slot="toast"]')
    if (!root || !button) return
    // A short delay simulates a request without sending data.
    const operation = new Promise<string>((resolve, reject) => {
      setTimeout(() => {
        if (button.dataset.toastPromise === "error")
          reject(new Error("The export failed. Try again."))
        else resolve("Your report is ready to download.")
      }, 1200)
    })
    createToast(root).promise(operation, {
      loading: "Preparing report…",
      success: (description) => ({ title: "Report ready", description }),
      error: (error) => ({
        title: "Could not export report",
        description: (error as Error).message,
      }),
    })
  })
</script>
```

### Position

Use `position` to select one of six viewport positions. Notifications expand when hovered or focused. Older notifications remain mounted but become hidden and inert when the visible limit is exceeded.

```astro
---
import type { ToastPosition } from "@data-slot/toast"
import { Button } from "@/components/ui/button"
import { Toast } from "@/components/ui/toast"

const positions: ToastPosition[] = [
  "top-left",
  "top-center",
  "top-right",
  "bottom-left",
  "bottom-center",
  "bottom-right",
]
---

<div data-toast-positions-demo class="flex flex-wrap justify-center gap-2">
  {positions.map((position) => (
    <>
      <Button variant="outline" data-toast-position-trigger={position}>
        {position.replace("-", " ")}
      </Button>
      <Toast position={position} data-toast-position-stack={position} />
    </>
  ))}
</div>

<script>
  import { createToast } from "@data-slot/toast"

  document.addEventListener("click", (event) => {
    const button = (event.target as Element).closest<HTMLElement>(
      "[data-toast-position-trigger]",
    )
    const demo = button?.closest("[data-toast-positions-demo]")
    if (!demo || !button) return
    for (const root of demo.querySelectorAll<HTMLElement>(
      "[data-toast-position-stack]",
    )) {
      const toaster = createToast(root)
      toaster.dismissAll()
      if (
        root.dataset.toastPositionStack === button.dataset.toastPositionTrigger
      ) {
        toaster.show({
          title: "Notification position",
          description: button.textContent?.trim(),
        })
      }
    }
  })
</script>
```

## Custom template

The default slot replaces both the template and viewport. Keep one `ToastTemplate` and one `ToastViewport` inside the root. `ToastTemplate` has its own default content, which you can replace with the exported parts:

```astro
<Toast>
  <ToastTemplate>
    <ToastItem>
      <ToastContent>
        <ToastTitle />
        <ToastDescription />
      </ToastContent>
      <ToastAction />
      <ToastClose aria-label="Dismiss notification" />
    </ToastItem>
  </ToastTemplate>
  <ToastViewport aria-label="Project notifications" />
</Toast>
```

Import these parts from `@/components/ui/toast`. The primitive fills the title, description, and action with text. It hides an empty description or action. Keep these slots free of child markup that must survive an update. Avoid fixed IDs inside the template because each notification clones it.

## API reference

### ToastProps

<AutoTypeTable path="../../packages/ui/src/components/ui/toast/types.ts" name="ToastProps" />

### ToastShowOptions

<AutoTypeTable path="../../packages/ui/src/components/ui/toast/types.ts" name="ToastShowOptions" />

### ToastUpdateOptions

<AutoTypeTable
    path="../../packages/ui/src/components/ui/toast/types.ts"
    name="ToastUpdateOptions"
/>

### ToastAction

<AutoTypeTable path="../../packages/ui/src/components/ui/toast/types.ts" name="ToastAction" />

### ToastPromiseOptions

<AutoTypeTable
    path="../../packages/ui/src/components/ui/toast/types.ts"
    name="ToastPromiseOptions"
/>

Other parts accept their native HTML attributes and `class`. `ToastViewport` is an ordered list. `ToastItem` is a list item. `ToastAction` and `ToastClose` are buttons. `ToastIcon` supplies the status icons, including the loading indicator.

### Events

Dispatch these events on the toast root. The root emits the outbound events.

#### Outbound events

| Event          | Detail                                        |
| -------------- | --------------------------------------------- |
| `toast:change` | `{ id: string, action: "show" \| "dismiss" }` |
| `toast:action` | `{ id: string, value: string \| undefined }`  |

#### Inbound events

| Event           | Detail                                |
| --------------- | ------------------------------------- |
| `toast:show`    | `ToastShowOptions`                    |
| `toast:update`  | `{ id: string } & ToastUpdateOptions` |
| `toast:dismiss` | `{ id: string }` or `string`          |
| `toast:clear`   | none                                  |

### Controller

Import `createToast` and controller types from `@data-slot/toast`. Use `show`, `update`, `promise`, `dismiss`, and `dismissAll` to control notifications. A repeated `show()` ID replaces the old toast; `update(id, patch)` changes it in place. Set `duration: 0` to keep a notification open until dismissed.

The root also accepts `toast:show`, `toast:update`, `toast:dismiss`, and `toast:clear` custom events. It emits `toast:change` and `toast:action`. See the [data-slot Toast API](https://data-slot.com/components/toast/) for options and event details.

Read the [installed source](/r/toast.json) for all exported parts.

## Accessibility and limits

The primitive announces errors and warnings as alerts. Other notifications use polite status announcements. Keep essential errors next to the affected field as well. Timers pause on hover, focus, window blur, and a hidden document. Users can close a toast with its labeled button or a swipe. `dismissible: false` disables swiping; it does not remove the close button.

The styles adapt [Coss Toast](https://coss.com/ui/docs/components/toast) to Astro and data-slot. This component uses the data-slot API. Anchored toasts, Base UI providers, F6 viewport focus, and Escape dismissal are not supplied. Animation follows the reduced-motion preference.

`portal` defaults to `true` in this Astro component, so the viewport can escape clipping containers. The primitive itself defaults to `false`. Set `portal={false}` to retain the viewport in its original parent; it still uses fixed positioning unless you supply a different layout class.

## Theme and layout

Toast styles use the project preset. Keep messages short enough to read at phone widths, and choose a viewport position that does not cover the main page action. Portalled toasts can escape clipping containers. Use an [Alert](/components/alert) for feedback that must remain in the page content.
