@codewithrajat/rm-toast-notification

August 1, 2026 · View on GitHub

npm version TypeScript SSR safe Security hardened MIT license npm downloads Production ready Strict TS Tree-shakable No side effects Linting Tests Coverage Accessibility compliant No dependencies Last update Maintained SemVer


See It In Action

rm-pushnotify Demo
rm-pushnotify Demo

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


Live Demo & Playground

StackBlitz Demo

Interactive Playground
Try all features live in your browser
GitHub Examples

Complete Examples
Copy-paste ready code samples
npm Package

npm Registry
Install and view package details
GitHub Repository

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 typessuccess, error, warning, and info, each with a distinct default color
  • 4 screen positionstop-left, top-right, bottom-left, and bottom-right
  • Auto-dismiss — configurable duration with a restart-safe timer; set duration: 0 for 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 animation option
  • Hover feedback — subtle scale and shadow effects on hover to signal interactivity
  • Programmatic controlcloseToast(), clearAll(), and destroy() 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 as expression(), url(javascript:...), @import, behavior, and -moz-binding are removed
  • URL validation — logo URLs are restricted to http:, https:, and data: 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 textContent rather than innerHTML

SSR & Compatibility

  • SSR-safe — gracefully no-ops when document or document.body is 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: false for 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.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

MethodDescription
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

OptionTypeDescriptionDefault
typestringNotification type. Available options: success, error, warning, info.info
positionstringPosition of the toast on the screen. Available options: top-left, top-right, bottom-left, bottom-right.top-right
durationnumberDuration in milliseconds to show the toast. Set to null for a permanent toast.3000
headerstringThe header text for the notification. (Optional)
bodystringThe body content. Can be plain text or sanitized HTML.
footerstringThe footer text. (Optional)
logostringURL of the logo image. (Optional)
colorstringCustom background color. (Optional)
onClickfunctionCustom click event handler for the notification. (Optional)
actionButtonobjectCustom action button with text and onClick function. (Optional)
animationbooleanEnable 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 @import are blocked
  • Logo URLs are validated to allow only safe schemes
  • Custom colors are restricted to safe formats
  • Text values are inserted using textContent where 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

BrowserVersionSupport LevelNotes
Chrome80+Full SupportRecommended browser
Firefox75+Full SupportWorks perfectly
Safari13+Full SupportiOS and macOS
Edge80+Full SupportChromium-based
Opera67+Full SupportWorks well
Samsung Internet12+Full SupportMobile support

Mobile Support

  • iOS Safari 13+
  • Chrome for Android 80+
  • Samsung Internet
  • All mobile browsers with modern JavaScript support

Download Behavior by Platform

PlatformBehavior
Desktop Chrome/Firefox/EdgeDirect download to Downloads folder
Desktop SafariMay prompt for download location
iOS SafariOpens download manager
Android ChromeDownloads to Downloads folder
Mobile SafariShows share sheet with save option

Not Supported

  • Internet Explorer (all old versions)
  • Very old mobile browsers (pre-2019)

Statistics

npm downloads npm version GitHub issues GitHub stars License


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.

GitHub GitHub followers GitHub stars


Support and Community

Getting Help

Need assistance? We're here to help!

Support ChannelLinkBest For
Bug ReportsReport BugTechnical issues
Feature RequestsRequest FeatureNew features
DiscussionsJoin DiscussionGeneral questions
Emailmr.rajatmalik@gmail.comDirect 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

LibraryDescriptionnpm Link
rm-range-sliderLightweight two-thumb range slider with tooltips and color customizationnpm
rm-ng-range-sliderAngular-specific version of the dual range slidernpm
rm-carouselSimple, responsive carousel componentnpm
rm-image-sliderMinimal image slider with smooth transitionsnpm
rm-ng-star-ratingConfigurable Angular star rating component with readonly modenpm
@codewithrajat/rm-ng-typeaheadAngular autocomplete/typeahead component with search suggestions and keyboard navigationGitHub
@codewithrajat/rm-ng-editorRich text editor component for Angular applications with customizable toolbar supportGitHub

PDF & Export Libraries

LibraryDescriptionnpm Link
rm-ng-export-to-csvExport JSON data to CSV with zero dependenciesnpm
@codewithrajat/rm-ng-pdf-exportImage-based PDF export tool for Angular applicationsnpm
@codewithrajat/rm-ng-structure-pdfGenerate structured PDFs for reports, invoices, or documentsnpm
@codewithrajat/rm-ng-pdf-viewerAngular PDF viewer component with zoom, navigation, and document rendering supportGitHub

Chrome Extension

LibraryDescriptionLink
quickocrChrome extension that extracts text from images using OCR technologyGitHub
readLoudeChrome extension that read you web page loude e.g article etc.GitHub
ai-assistant-replyAI Chrome extension to auto generate reply on linked in posts.GitHub

VS Code Extension

LibraryDescriptionLink
dead-css-cleanerVS Code extension for identifying and cleaning unused CSS stylesGitHub
file-coverage-insightVS Code extension for auto generated component file coverage automatelly on open.GitHub

Desktop Applications - All Plateform

LibraryDescriptionLink
deepworkCross-platform productivity application for focus sessions and deep work trackingGitHub
JsSandboxCross-platform JavaScript playground and code execution environmentGitHub

Device Detection

LibraryDescriptionnpm Link
rm-ng-device-detectionDetect device type, OS, and browser in Angularnpm

Notifications

LibraryDescriptionnpm Link
rm-pushnotifyLightweight push-style toast notification utilitynpm
@codewithrajat/rm-toast-notificationCross-platform toast and desktop notification library for web, Angular, and desktop applicationsGitHub

Layout & Dynamic Rendering

LibraryDescriptionLink
rm-ng-dynamic-layoutDynamic layout rendering engine for Angular applications using JSON-driven UI configurationGitHub

Developer Tools & Extensions

LibraryDescriptionLink
rm-colorful-console-loggerStructured and colorized console logging utility for developersnpm

Meta & Personal Branding

LibraryDescriptionnpm Link
about-rajatDeveloper portfolio package for branding and quick personal infonpm

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

SOCIAL PRESENCE

CONTENT & WRITING


Made with care and love by Rajat Malik for the community

Star on GitHubView on npmReport Issue

Made with dedication by Rajat Malik