Skip to content

hc-oss/next-nookies-persist

Repository files navigation

next-nookies-persist

A simple easy to digest key-value based storage module wrapper for Next.js based on cookies that persists data on page reloads

Example

GitHub Actions Status NPM gzip

as this package is written in TypeScript documentation is directly available as jsdoc/tsdoc intellisense

⚡ Features

  • SSR Ready
  • Store JSON Out of the box
  • Lightweight
  • Typed with TypeScript (works with JavaScript too)

🔧 Installation

npm i next-nookies-persist

📦 Usage

Configure pages/_app.js

import App from "next/app";
import React from "react";

import { NookiesProvider, parseNookies } from "next-nookies-persist";

export default class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    return {
      pageProps: {
        nookies: parseNookies(ctx), // 👈
        ...(Component.getInitialProps
          ? await Component.getInitialProps(ctx)
          : {})
      }
    };
  }

  render() {
    const { Component, pageProps } = this.props;

    return (
      <NookiesProvider initialValue={pageProps.nookies}> // 👈
        <Component {...pageProps} />
      </NookiesProvider>
    );
  }
}

Use as a react hook inside component pages/index.js

import React from "react";

import useStorage from "next-nookies-persist";

const Home = () => {
  const { nookies, setNookie, removeNookie } = useStorage();

  return (
    <div>
      <pre>{JSON.stringify(nookies, null, 2)}</pre>
      <button onClick={() => setNookie("foo", { bar: "baz" })}>Set</button>
      <button onClick={() => removeNookie("foo")}>Clear</button>
    </div>
  );
};

export default Home;

Demo

🤠 Credits

🙏 Contributing

Contributions/Suggestions are always welcome!

📄 License

MIT © harshzalavadiya