@codewithrajat/rm-toast-notification
August 1, 2026 · View on GitHub
See It In Action
A lightweight, customizable, and secure toast notification library for web applications with auto-dismiss, custom colors, logos, action buttons, and built-in XSS protection.
Overview
@codewithrajat/rm-toast-notification is a lightweight, framework-agnostic toast notification library for modern web applications. It provides a zero-config, fully typed TypeScript API that works seamlessly with plain JavaScript, TypeScript, React, Angular, Vue, and Svelte.
Built with security and accessibility as first-class concerns, the library sanitizes all HTML content through DOMPurify, guards against XSS and CSS injection attacks, validates logo URLs and custom colors, and ships an accessible close button with proper ARIA labels.
Table of Contents
- Features
- Live Demo & Playground
- Installation
- Quick Start
- Usage Examples
- API
- Security
- FAQ
- Browser Support
- Changelog
- License
- Support & Community
- Author
- Other Libraries
Live Demo & Playground
|
Interactive Playground Try all features live in your browser |
Complete Examples Copy-paste ready code samples |
|
npm Registry Install and view package details |
Source Code Star, fork, and contribute |
Features
- Framework-agnostic and dependency-light
- Fully typed with TypeScript
- SSR-safe: no crash when the document is unavailable
- Auto-dismiss with configurable duration
- Pause on hover while the toast is active
- Four toast types: success, error, warning, info
- Four positions: top-left, top-right, bottom-left, bottom-right
- Custom background color support
- Optional logo image support
- Optional action button with click handler
- Safe HTML body rendering via DOMPurify
- CSS injection protection for body content and style values
- Accessibility-friendly close button with aria label
- Clear-all and destroy helpers for app teardown
Key Capabilities
- 4 toast types —
success,error,warning, andinfo, each with a distinct default color - 4 screen positions —
top-left,top-right,bottom-left, andbottom-right - Auto-dismiss — configurable duration with a restart-safe timer; set
duration: 0for persistent toasts - Pause on hover — the auto-dismiss timer pauses while the mouse is over a toast and resumes on leave, giving users time to read longer messages
- Rich content — optional header, body, footer, and custom logo image per toast
- Action buttons — attach a custom action button with its own click handler that never triggers the toast-level click
- Custom styling — per-toast background colors with strict hex/rgb/rgba validation
- Toast-level click handling — trigger a callback when the toast itself is clicked (button clicks are automatically excluded)
- Animated transitions — slide-in/slide-out animations per position, toggleable via the
animationoption - Hover feedback — subtle scale and shadow effects on hover to signal interactivity
- Programmatic control —
closeToast(),clearAll(), anddestroy()for full lifecycle management, ideal for SPA route changes and app teardown
Security Features
- XSS protection — body HTML is sanitized through DOMPurify, stripping dangerous tags (
script,iframe,object,embed,link,meta,base,form,style), inline style/class/id and event-handler attributes, and disabling data attributes - CSS injection protection — inline styles and
<style>blocks are scrubbed; dangerous patterns such asexpression(),url(javascript:...),@import,behavior, and-moz-bindingare removed - URL validation — logo URLs are restricted to
http:,https:, anddata:protocols only - Color validation — custom colors must match strict hex or rgb/rgba patterns
- Safe DOM insertion — text fields (header, footer, close button, action button) use
textContentrather thaninnerHTML
SSR & Compatibility
- SSR-safe — gracefully no-ops when
documentordocument.bodyis unavailable, preventing crashes during server-side rendering - Container reuse — a shared toast container is reused across instances to avoid DOM duplication
- Tree-shakable — ESM module with
sideEffects: falsefor optimal bundle sizes - Modern browsers — works in all evergreen browsers including Chrome, Firefox, Safari, and Edge
Installation
npm install @codewithrajat/rm-toast-notification
pnpm add @codewithrajat/rm-toast-notification
yarn add @codewithrajat/rm-toast-notification
## Quick Start
import ToastNotification from '@codewithrajat/rm-toast-notification';
const toast = new ToastNotification();
toast.showToast({
type: 'success',
header: 'Saved',
body: 'Your changes were saved successfully.',
position: 'top-right',
duration: 3000,
});
Usage Examples
Basic toast
const toast = new ToastNotification();
toast.showToast({
type: 'info',
body: 'Hello from rm-toast-notification',
});
Toast with header, footer, and custom logo
toast.showToast({
type: 'warning',
header: 'Heads up',
body: 'Your session will expire soon.',
footer: 'Please save your work',
logo: 'https://example.com/icon.png',
position: 'bottom-right',
});
Toast with action button
toast.showToast({
type: 'error',
header: 'Upload failed',
body: 'Please try again.',
duration: 0,
actionButton: {
text: 'Retry',
onClick: () => console.log('Retry clicked'),
},
});
Custom color
toast.showToast({
type: 'info',
body: 'Custom styled toast',
color: '#6366f1',
});
Persistent toast
toast.showToast({
type: 'warning',
body: 'This toast stays until you close it.',
duration: 0,
});
Programmatic control
const toastElement = toast.showToast({
type: 'success',
body: 'This toast can be closed manually.',
});
toast.closeToast(toastElement!);
toast.clearAll();
toast.destroy();
Examples 1
Create a service and reuse it.
import ToastNotification from 'rm-toast-notification';
const toastService = new ToastNotification();
toastService.showToast({
type: 'info', // Notification type (success, error, warning, info)
position: 'top-right', // Position of the toast (top-left, top-right, bottom-left, bottom-right)
duration: 3000, // Duration in milliseconds (null for permanent)
header: 'Information', // Header text (optional)
body: 'This is a simple toast notification.', // Body content (can be plain text or HTML)
footer: 'Footer content (optional)', // Footer text (optional)
logo: 'https://example.com/logo.png', // Logo image (optional)
color: '', // Custom background color (optional)
actionButton: { // Action button (optional)
text: 'Action',
onClick: () => alert('Action clicked!'),
},
onClick: (e) => { // Custom onClick event (optional)
console.log('Toast clicked', e);
},
animation: true // Animation for appearance (true or false)
});
Example with Action Button
toastService.showToast({
type: 'success',
position: 'bottom-left',
duration: 4000,
header: 'Success!',
body: 'You have successfully completed the task.',
actionButton: {
text: 'Undo',
onClick: () => alert('Undo clicked!'),
},
});
Example with HTML Content
toastService.showToast({
type: 'error',
position: 'top-right',
duration: 5000,
body: '<strong>Error!</strong> <p>An unexpected error occurred.</p>',
});
API
ToastNotification
const toast = new ToastNotification();
Methods
| Method | Description |
|---|---|
showToast(options) | Displays a toast and returns the DOM element |
closeToast(toast) | Closes a specific toast safely |
clearAll() | Closes all active toasts |
destroy() | Removes the toast container and clears resources |
Toast options
| Option | Type | Description | Default |
|---|---|---|---|
type | string | Notification type. Available options: success, error, warning, info. | info |
position | string | Position of the toast on the screen. Available options: top-left, top-right, bottom-left, bottom-right. | top-right |
duration | number | Duration in milliseconds to show the toast. Set to null for a permanent toast. | 3000 |
header | string | The header text for the notification. (Optional) | |
body | string | The body content. Can be plain text or sanitized HTML. | |
footer | string | The footer text. (Optional) | |
logo | string | URL of the logo image. (Optional) | |
color | string | Custom background color. (Optional) | |
onClick | function | Custom click event handler for the notification. (Optional) | |
actionButton | object | Custom action button with text and onClick function. (Optional) | |
animation | boolean | Enable or disable animation for showing the toast. | true |
Security
This package is built with security in mind.
- HTML content is sanitized through DOMPurify
- Inline style attributes and style blocks are stripped from body content
- Dangerous CSS expressions such as
expression(),url(javascript:...), and@importare blocked - Logo URLs are validated to allow only safe schemes
- Custom colors are restricted to safe formats
- Text values are inserted using
textContentwhere appropriate
Changelog
See CHANGELOG.md for release history and updates.
Latest Release
Check the releases page for the most recent version and updates.
License
This project is licensed under the MIT License - see the LICENSE file for details.
TL;DR: You can use this library freely in commercial and personal projects.
MIT License Summary
You can:
- Use commercially
- Modify the code
- Distribute
- Use privately
You must:
- Include the license and copyright notice
You cannot:
- Hold the author liable
FAQ
What is rm-toast-notification?
It is a lightweight, framework-agnostic toast notification library for web apps, built with TypeScript and designed for zero-config usage. It supports plain JavaScript, React, Angular, Vue, and Svelte, and ships with full type definitions for TypeScript projects.
Does the library have dependencies?
The library source imports a single runtime dependency, DOMPurify, which is used to sanitize HTML content before it is inserted into the DOM. There are no other runtime imports, keeping the bundle small and focused.
Which frameworks does it support?
It works with plain JavaScript, TypeScript, React, Angular, Vue, and Svelte. Because the library is framework-agnostic and DOM-based, you can use it anywhere you have access to the DOM — including inside framework services, components, or utility modules.
How do I create a persistent toast that never auto-dismisses?
Set duration: 0 (or a negative value). The toast stays on screen until the user clicks the close button, clicks the toast body, or you call clearAll() / destroy() programmatically.
Is it safe to render HTML in the body?
Yes, but it is sanitized before being inserted into the DOM. The body option is passed through DOMPurify with dangerous tags (script, iframe, object, embed, link, meta, base, form, style) stripped, inline style/class/id and event-handler attributes removed, and data attributes disabled. You can safely pass simple rich content such as <strong>, <em>, or <p>.
Can I customize the look of a toast?
Yes. Use the color option for custom background colors, the logo option for a custom icon/logo image, and the body option for safe HTML content. Header and footer text are inserted as plain text to prevent XSS. Custom colors must be valid hex (#fff, #ffffff, #ffffffff) or rgb()/rgba() values.
What happens when the user hovers over a toast?
The auto-dismiss timer pauses while the mouse is over the toast and resumes when the mouse leaves. The toast also shows a subtle scale/shadow hover effect to signal interactivity. Hover handlers use relatedTarget checks so they don't fire incorrectly when moving between child elements.
Can I attach an action button to a toast?
Yes. Use the actionButton option with text and onClick. The button's click handler fires independently, and clicks on the action button do not trigger the toast-level onClick or close the toast — preventing accidental dismissal while interacting with the button.
Can I trigger an action when the whole toast is clicked?
Yes. Use the onClick option to provide a click handler for the toast itself. Clicks originating from buttons (the close button or action button) are automatically excluded so they don't accidentally trigger the toast-level handler, and the toast auto-closes after the handler runs.
Is it SSR-safe?
Yes. The library guards against missing document access during server rendering. If document or document.body is unavailable (for example during SSR in Next.js, Nuxt, or Angular Universal), showToast() safely returns null instead of crashing.
How do I handle multiple toast instances or SPA route changes?
The library reuses a single shared container, so you can create multiple ToastNotification instances without duplicating the DOM container. For SPA route changes or app teardown, call destroy() to remove the container and clear all active toasts, or clearAll() to remove all toasts while keeping the container available.
Can I disable animations?
Yes. Set animation: false in the toast options to disable the slide-in animation. Positioning and layout remain intact — only the keyframe animation is skipped.
Can I access default colors or animations programmatically?
Yes. The library exposes public utility methods: getColor(type) returns the default color for a toast type, getAnimation(position) returns the slide-in CSS animation value for a position, and getActionButtonColor(type) returns the default action button color for a toast type — useful for aligning custom styling with the library's defaults.
Is the close button accessible?
Yes. The close button is a real <button> element with type="button" and an aria-label="Close notification", making it accessible to screen readers and keyboard users.
What browsers are supported?
The library targets modern evergreen browsers: Chrome 80+, Firefox 75+, Safari 13+, Edge 80+, Opera 67+, and Samsung Internet 12+. Internet Explorer and pre-2019 legacy browsers are not supported.
How do I import the library?
import ToastNotification from '@codewithrajat/rm-toast-notification';
The package ships as an ESM module with TypeScript type definitions included, so autocomplete and type checking work out of the box.
Browser Support
The library targets modern browsers and works well in:
- Chrome
- Edge
- Firefox
- Safari
- Mobile browsers with modern JavaScript support
Browser Compatibility
Supported Browsers
| Browser | Version | Support Level | Notes |
|---|---|---|---|
| Chrome | 80+ | Full Support | Recommended browser |
| Firefox | 75+ | Full Support | Works perfectly |
| Safari | 13+ | Full Support | iOS and macOS |
| Edge | 80+ | Full Support | Chromium-based |
| Opera | 67+ | Full Support | Works well |
| Samsung Internet | 12+ | Full Support | Mobile support |
Mobile Support
- iOS Safari 13+
- Chrome for Android 80+
- Samsung Internet
- All mobile browsers with modern JavaScript support
Download Behavior by Platform
| Platform | Behavior |
|---|---|
| Desktop Chrome/Firefox/Edge | Direct download to Downloads folder |
| Desktop Safari | May prompt for download location |
| iOS Safari | Opens download manager |
| Android Chrome | Downloads to Downloads folder |
| Mobile Safari | Shows share sheet with save option |
Not Supported
- Internet Explorer (all old versions)
- Very old mobile browsers (pre-2019)
Statistics
Support This Project
If rm-toast-notification has helped you build better applications, please consider:
If this library has saved you development time and helped create amazing projects, please consider giving it a star!
Why star this repo?
- Help other developers discover this lightweight, optimized solution
- Support continued development and improvements
- Show appreciation for free, quality tools
- Boost visibility in the community
- Increases visibility in the community
- Supports ongoing development and maintenance
- Encourages more open-source contributions
- Helps other developers find quality tools
Want More Quality Libraries?
This is just one of several useful libraries I've created. Explore my other web development libraries that might solve your next challenge:
- Utility libraries for common development tasks
- UI components for better user experiences
- Performance tools for optimization
- Mobile-friendly solutions for responsive apps
Found them helpful? A star on each repo you find useful helps tremendously! It takes just one click but means the world to open-source maintainers.
Support and Community
Getting Help
Need assistance? We're here to help!
| Support Channel | Link | Best For |
|---|---|---|
| Bug Reports | Report Bug | Technical issues |
| Feature Requests | Request Feature | New features |
| Discussions | Join Discussion | General questions |
| mr.rajatmalik@gmail.com | Direct support |
Documentation
Community
- Star the repository to show support
- Watch for updates and new releases
- Share your use cases and feedback
- Contribute code or documentation
Stay Updated
- Follow the project on GitHub
- Star the repository for updates
- Watch for new releases
Acknowledgments
This library was created to provide a simple, a lightweight, customizable, and secure toast notification library for web applications. It helps you show short-lived messages with auto-dismiss, custom colors, logos, action buttons, animated positions, and built-in protection against XSS and CSS injection.
Special thanks to:
- Contributors - Thank you for making this library better
- Community - For feedback and feature requests
Other Libraries
UI Components
PDF & Export Libraries
Chrome Extension
VS Code Extension
Desktop Applications - All Plateform
| Library | Description | Link |
|---|---|---|
| deepwork | Cross-platform productivity application for focus sessions and deep work tracking | |
| JsSandbox | Cross-platform JavaScript playground and code execution environment |
Device Detection
| Library | Description | npm Link |
|---|---|---|
| rm-ng-device-detection | Detect device type, OS, and browser in Angular |
Notifications
Layout & Dynamic Rendering
| Library | Description | Link |
|---|---|---|
| rm-ng-dynamic-layout | Dynamic layout rendering engine for Angular applications using JSON-driven UI configuration |
Developer Tools & Extensions
| Library | Description | Link |
|---|---|---|
| rm-colorful-console-logger | Structured and colorized console logging utility for developers |
Meta & Personal Branding
| Library | Description | npm Link |
|---|---|---|
| about-rajat | Developer portfolio package for branding and quick personal info |
All Packages
Browse all my packages:
Author
Rajat Malik
Full‑Stack Developer and Frontend Architect at Siemens with 14+ years building scalable enterprise platforms, specializing in micro‑frontends, AI‑native development, React, and Angular.
Author of 10+ open‑source libraries and 100+ technical articles, driving innovation through developer‑friendly tools, performance optimization, and AI‑assisted workflows.
GET IN TOUCH
- Portfolio: rajatmalik.dev
- Email: mr.rajatmalik@gmail.com
- LinkedIn: errajatmalik
- GitHub: @malikrajat
- npm: rajatmalik
SOCIAL PRESENCE
- Threads: rajatmalik
- Twitter/X: rajatmalik
- BlueSky: rajatmalik
CONTENT & WRITING
- Medium: rajatmalik
- Dev.to: rajatmalik
- Substack: rajatmalik
- Hashnode: rajatmalik
Made with care and love by Rajat Malik for the community
Star on GitHub • View on npm • Report Issue
Made with dedication by Rajat Malik