npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@thewebartisan7/next-flash-message

v1.0.1

Published

NextJS Flash Message

Downloads

73

Readme

NextJS Flash Message

A lightweight package for managing flash messages in Next.js applications. Flash messages allow you to pass messages between requests by storing them in cookies. This package supports one flash message at a time, making it simple and efficient.

It integrates seamlessly with Sonner for displaying toast notifications, but you are free to use any library or custom UI implementation.

Installation

To use the package, first install it via npm or yarn:

npm install @thewebartisan7/next-flash-message
# or
yarn add @thewebartisan7/next-flash-message

Features

  • Supports multiple levels: info, success, warning, and error.
  • Optional support for additional details like descriptions and custom durations.
  • Flexible: Works with any UI library for displaying messages.
  • Pre-built integration with Sonner for toast notifications.

Basic usage

Server Action Example

Here's an example of a server action that sets a flash message and redirects:

"use server";

import { flashMessage } from "next-js-flash-message";
import { redirect } from "next/navigation";

export const anAction = async (formData: FormData) => {
  // Handle action logic

  // Set a flash message
  await flashMessage("Successfully processed action");

  // Redirect
  redirect("/");
};

Client Component Example

In your client component, retrieve and display the flash message:

'use client';

import { useEffect } from "react";
import { flashMessage } from "next-js-flash-message";

export default function ClientComponent() {
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    const showFlashMessage = async () => {
      const flash = await flashMessage();

      if (flash) {
        setMessage(flash.message);
      }
    };

    showFlashMessage();
  }, []);

  return <>{message && <div>{message}</div>}</>;
}

Using the Sonner Toast Library

Setting Up Sonner with ToasterProvider

To integrate with Sonner, start by adding the ToasterProvider to your layout:

Inside your layout add Sonner toast provider like shown below:

import { ToasterProvider } from "next-js-flash-message/components";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        {children}
        <ToasterProvider />
      </body>
    </html>
  );
}

NOTE: If you already use the Sonner components from shadcn/ui, continue using them. This package's components are compatible with those.

Displaying Flash Messages with FlashMessageProvider

Add the FlashMessageProvider to your page or component to handle message retrieval and display:

import { Form } from "@/components/form";
import { FlashMessageProvider } from "next-js-flash-message/components";

export default function Homepage() {
  return (
    <div>
      <main>
        <Form />
        <FlashMessageProvider />
      </main>
    </div>
  );
}

Note: The FlashMessageProvider automatically listens for and displays flash messages using Sonner.

Complete Example with Form

Here's a complete example including a form that triggers a server action:

"use client";

import { anAction } from "@/actions/an-action";

export const Form = () => {
  return (
    <form action={anAction}>
      <input name="name" type="text" placeholder="Enter your name" />
      <button type="submit">Submit</button>
    </form>
  );
};

Using the useFlashMessage Hook

Instead of adding the FlashMessageProvider to your page, you can directly use the useFlashMessage hook to handle flash message retrieval and display.

Example: Using useFlashMessage with Sonner

Here's how to use the useFlashMessage hook to display flash messages with Sonner:

"use client";

import { anAction } from "@/actions/an-action";
import { useFlashMessage } from "next-js-flash-message/hooks";

export const Form = () => {
  // Retrieve and display the flash message using Sonner toast
  useFlashMessage();

  return (
    <form action={anAction}>
      <input name="name" type="text" placeholder="Enter your name" />
      <button type="submit">Submit</button>
    </form>
  );
};

Flash message API

The flashMessage function supports various configurations:

Basic Examples

// Simple message
await flashMessage("My awesome flash message");

// With level
await flashMessage("Action successful", "success");

// With a description
await flashMessage("Error occurred", "error", "Please try again.");

Object-Based Configuration

await flashMessage({
  message: "Action required",
  level: "info",
  description: "More details about this message.",
});

Additional Options

Customize your flash messages:

await flashMessage({
  message: "Custom duration and position",
  level: "warning",
  description: "This message lasts for 3 seconds.",
  duration: 3000,
  position: "top-center", // Options: "top-left", "top-center", "top-right", etc.
  closeButton: true,
});

Persistent Toasts

Keep toasts visible until manually dismissed:

// Using an object you can pass additional options, only the message is mandatory
await flashMessage({
  message: "Persistent message",
  duration: Infinity,
  closeButton: true, // Optionally allow users to dismiss it manually
});

Testing

This package includes comprehensive tests to ensure reliability across all documented use cases.

Run tests using:

npm test

Credits and Acknowledgments

Thanks to Robin Wieruch for his insightful tutorials on Next.js.

Kudos to Emil Kowalski for the amazing Sonner toast library.

Feel free to contribute, report issues, or suggest improvements via the GitHub repository. Happy coding! 🚀