Skip to main content

Toast

Temporary notification messages that appear and disappear automatically

Tags:
toastnotificationsfeedbackalertstemporary
Last updated: 2025-09-25T00:00:00.000Z

Toast Notifications

Toast notifications provide temporary feedback about actions or events. They appear briefly, don’t interrupt the user’s workflow, and disappear automatically or can be manually dismissed.

Overview

The Toast component delivers lightweight, contextual feedback that appears at the edge of the screen. Unlike alerts or modals, toasts are non-blocking and designed to communicate status updates, confirmations, or brief messages without requiring user interaction.

Interactive Demo

Basic Toast

Simple notification with title and message

Success Toast

Click to trigger a real toast notification

toast.success("Changes saved!", { title: "Success" })

Usage

Basic Implementation

<script>
import Toast from '$lib/notification/components/Toast.svelte';

const notification = {
  id: 'unique-id',
  type: 'success',
  title: 'Success',
  message: 'Changes saved successfully',
  duration: 5000,
  position: 'top-right',
  dismissible: true,
  createdAt: new Date(),
  priority: 1
};
</script>

<Toast
  {notification}
  onDismiss={(id) => handleDismiss(id)}
/>

Using the Toast Hook

The recommended way to show toasts is through the useToast() hook:

<script>
import { useToast } from '$lib/notification/components/use-toast';

const toast = useToast();

async function saveData() {
  try {
    await api.saveData();
    toast.success('Data saved successfully');
  } catch (error) {
    toast.error('Failed to save data');
  }
}
</script>

<button onclick={saveData}>Save</button>

With ToastProvider

Wrap your app with ToastProvider to enable the toast system:

<!-- app.html or +layout.svelte -->
<script>
import { ToastProvider } from '$lib/notification/components';
</script>

<ToastProvider>
  <!-- Your app content -->
  <main>
    <!-- Components can now use useToast() -->
  </main>
</ToastProvider>

Toast Types

Success

Confirm successful operations and completed actions.

When to use:

  • Form submissions completed
  • Files uploaded successfully
  • Settings saved
  • Actions completed

Error

Indicate failures or problems that need attention.

When to use:

  • API request failures
  • Validation errors
  • Network issues
  • Permission errors

Warning

Alert users to potential issues or important considerations.

When to use:

  • Quota limits approaching
  • Temporary system issues
  • Deprecation notices
  • Action confirmations needed

Info

Provide helpful information or neutral status updates.

When to use:

  • Feature announcements
  • System status updates
  • General notifications
  • Process started messages

Features

Auto-dismiss with Progress

Toasts automatically disappear after their duration expires. A progress bar shows remaining time:

<Toast
  notification={{
    ...baseNotification,
    duration: 5000 // 5 seconds
  }}
  showProgress={true}
/>

Pause on Hover

Progress pauses when users hover over the toast, resuming when they move away:

// Built-in behavior - no configuration needed
// Progress automatically pauses on hover
// Resumes on mouse leave with remaining time

Action Buttons

Include action buttons for user interaction:

<script>
const notificationWithActions = {
  ...baseNotification,
  type: 'info',
  title: 'Update Available',
  message: 'A new version is ready to install',
  actions: [
    { id: 'install', label: 'Install' },
    { id: 'later', label: 'Later' }
  ]
};

function handleAction(notificationId, actionId) {
  if (actionId === 'install') {
    startInstall();
  }
  toast.dismiss(notificationId);
}
</script>

<Toast
  notification={notificationWithActions}
  onAction={handleAction}
/>

Swipe to Dismiss

Touch-enabled swipe gestures for mobile dismissal:

// Built-in on mobile devices
// Swipe left or right to dismiss
// Only works when dismissible: true

API Reference

Toast Props

PropTypeDefaultDescription
notificationNotificationRequiredThe notification object to display
onDismiss(id: string) => void-Callback when toast is dismissed
onAction(notificationId: string, actionId: string) => void-Callback when action button is clicked
showProgressbooleantrueWhether to show progress bar
classstring''Additional CSS classes

Notification Object

PropertyTypeDefaultDescription
idstringRequiredUnique identifier
type'success' \| 'error' \| 'warning' \| 'info'RequiredToast type
titlestring-Optional title
messagestringRequiredMain message text
durationnumber5000Auto-dismiss time in ms
positionNotificationPosition'top-right'Screen position
dismissiblebooleantrueCan be manually dismissed
actionsNotificationAction[]-Action buttons
prioritynumber1Display priority

useToast() API

MethodParametersDescription
success(message: string, options?: Partial<Notification>)Show success toast
error(message: string, options?: Partial<Notification>)Show error toast
warning(message: string, options?: Partial<Notification>)Show warning toast
info(message: string, options?: Partial<Notification>)Show info toast
dismiss(id: string)Dismiss specific toast
dismissAll()Dismiss all toasts

Positioning

Toasts can appear in six different positions:

const positions = [
  'top-left',    'top-center',    'top-right',
  'bottom-left', 'bottom-center', 'bottom-right'
];

// Usage
toast.success('Message', { position: 'bottom-center' });

Position Guidelines

  • top-right: Default, good for most notifications
  • top-center: Important system messages
  • bottom-right: Less intrusive for background processes
  • bottom-center: Mobile-friendly position

Patterns

Form Submission Feedback

<script>
import { enhance } from '$app/forms';
import { useToast } from '$lib/notification/components/use-toast';

const toast = useToast();
</script>

<form
  method="POST"
  use:enhance={({ formData, cancel }) => {
    return async ({ result, update }) => {
      if (result.type === 'success') {
        toast.success('Form submitted successfully');
      } else if (result.type === 'failure') {
        toast.error('Please fix the errors and try again');
      }
      await update();
    };
  }}
>
  <!-- Form fields -->
  <button type="submit">Submit</button>
</form>

API Request Handling

<script>
const toast = useToast();

async function fetchData() {
  toast.info('Loading data...');

  try {
    const response = await fetch('/api/data');

    if (response.ok) {
      toast.success('Data loaded successfully');
    } else {
      toast.error('Failed to load data');
    }
  } catch (error) {
    toast.error('Network error occurred');
  }
}
</script>

Undo Actions

<script>
let items = $state(['Item 1', 'Item 2', 'Item 3']);
const toast = useToast();

function deleteItem(index) {
  const item = items[index];
  items.splice(index, 1);

  toast.info(`Deleted "${item}"`, {
    duration: 8000,
    actions: [
      { id: 'undo', label: 'Undo' }
    ]
  }).then((notification) => {
    // Handle undo if implemented
  });
}
</script>

Accessibility

ARIA Attributes

  • role=“alert”: For error and warning toasts that need immediate attention
  • role=“status”: For success and info toasts with non-critical updates
  • aria-live: Automatically set based on toast type
  • aria-describedby: Links toast content to screen readers

Keyboard Support

  • Escape: Dismiss focused toast (when dismissible)
  • Tab: Navigate to action buttons within toast
  • Enter/Space: Activate action buttons

Screen Reader Considerations

  • Toast messages are announced immediately when they appear
  • Title and message are combined for complete context
  • Action buttons are properly labeled and accessible
  • Dismiss buttons have clear aria-labels

Best Practices

Do’s

Keep messages concise and actionable

  • Use clear, specific language
  • Provide next steps when appropriate
  • Avoid technical jargon

Use appropriate durations

  • Success: 3-5 seconds
  • Info: 5-7 seconds
  • Error: 8-10 seconds (or persistent)
  • Warning: 6-8 seconds

Position contextually

  • Use consistent positioning within your app
  • Consider mobile viewport constraints
  • Avoid covering important UI elements

Group related notifications

  • Combine similar actions where possible
  • Use priority to manage display order
  • Prevent notification spam

Don’ts

Don’t use for critical errors

  • Use modals for errors requiring immediate action
  • Reserve toasts for non-blocking feedback
  • Ensure critical messages persist

Don’t overwhelm users

  • Limit simultaneous toasts
  • Queue notifications appropriately
  • Consider notification fatigue

Don’t rely solely on color

  • Always include descriptive text
  • Use icons to reinforce meaning
  • Ensure sufficient contrast

Don’t interrupt workflows

  • Keep toasts non-modal
  • Allow interaction with underlying content
  • Provide easy dismissal options

Troubleshooting

Toasts not appearing

  • Verify ToastProvider is wrapping your app
  • Check that useToast() is called within provider context
  • Ensure notification object has required fields

Progress bar not working

  • Confirm showProgress prop is true
  • Check that duration is greater than 0
  • Verify dismissible is not false

Actions not triggering

  • Ensure onAction callback is provided
  • Check action IDs match between notification and handler
  • Verify action buttons are properly configured

Mobile gestures not working

  • Confirm touch events are not being intercepted
  • Check that dismissible is true
  • Verify swipe threshold is appropriate for device
  • SemanticAlert: Page-level alerts that persist
  • Tooltip: Contextual help on hover
  • Modal: Blocking dialogs requiring attention
  • EmptyState: Full-page feedback states