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

cookie-react

v0.0.5

Published

Cookie management library with token refreshing functionality.

Downloads

353

Readme

Cookie React

cookie-react is a simple and lightweight library for managing cookies in your React applications. It provides methods to set, get, remove, and update cookies, making it easy to handle client-side cookies.

Installation

To install cookie-react, use npm or yarn:

npm install cookie-react

or

yarn add cookie-react

Usage

Importing cookie-react

import {
  setCookie,
  getCookie,
  hasCookie,
  removeCookie,
  getAllCookies,
  clearAllCookies,
  updateTokens
} from 'cookie-react';

Setting a Cookie

To set a cookie, use the setCookie method:

setCookie("cookie_name", "cookie_value", {
  path: "/",
  expires: 3600, // Cookie expiry in seconds (1 hour)
  secure: true, // Use Secure flag
  sameSite: "Lax", // SameSite attribute
});

Getting a Cookie

To get the value of a cookie, use the getCookie method:

const value = getCookie("cookie_name");
console.log(value);

Removing a Cookie

To remove a cookie, use the removeCookie method:

removeCookie("cookie_name", {
  path: "/",
});

Updating Tokens

To update tokens dynamically, use the updateTokens method. This method refreshes tokens and updates them in cookies.

await updateTokens(
  currentToken, // Current token to refresh
  "https://your-api/refresh", // API endpoint to refresh tokens
  (rawTokens) => ({
    access: rawTokens.access_token,
    accessExpiresIn: rawTokens.access_expires_in,
    refresh: rawTokens.refresh_token,
    refreshExpiresIn: rawTokens.refresh_expires_in,
  }), // Function to format tokens
  {
    path: "/",
    secure: true,
    sameSite: "Lax",
  }
);

Example Component

Here’s a simple example React component demonstrating how to use cookie-react:

import React, { useState } from "react";
import { setCookie, getCookie, removeCookie, updateTokens } from "cookie-react";

const App: React.FC = () => {
  const [cookieValue, setCookieValue] = useState<string | null>(null);

  const handleSetCookie = () => {
    setCookie("my_cookie", "cookie_value", {
      path: "/",
      expires: 3600, // 1 hour
      secure: true,
      sameSite: "Lax",
    });
    alert("Cookie set!");
  };

  const handleGetCookie = () => {
    const value = getCookie("my_cookie");
    setCookieValue(value);
  };

  const handleRemoveCookie = () => {
    removeCookie("my_cookie", {
      path: "/",
    });
    setCookieValue(null);
  };

  const handleUpdateTokens = async () => {
    const currentToken = getCookie("refresh_token");
    const refreshUrl = "https://your-api/refresh"; // Replace with your API endpoint

    await updateTokens(
      currentToken || "",
      refreshUrl,
      (rawTokens) => ({
        access: rawTokens.access_token,
        accessExpiresIn: rawTokens.access_expires_in,
        refresh: rawTokens.refresh_token,
        refreshExpiresIn: rawTokens.refresh_expires_in,
      }),
      {
        path: "/",
        secure: true,
        sameSite: "Lax",
      }
    );
    alert("Tokens updated!");
  };

  return (
    <div>
      <h1>Cookie Manager</h1>
      <button onClick={handleSetCookie}>Set Cookie</button>
      <button onClick={handleGetCookie}>Get Cookie</button>
      <button onClick={handleRemoveCookie}>Remove Cookie</button>
      <button onClick={handleUpdateTokens}>Update Tokens</button>
      {cookieValue && <p>Cookie Value: {cookieValue}</p>}
    </div>
  );
};

export default App;

API Reference

setCookie(name: string, value: string, options: CookieOptions) Sets a cookie with the specified name, value, and options.

  • name: The name of the cookie.
  • value: The value of the cookie.
  • options: Optional cookie settings.

getCookie(name: string): string | null Gets the value of the specified cookie.

  • name: The name of the cookie.

removeCookie(name: string, options: CookieOptions) Removes the specified cookie.

  • name: The name of the cookie.
  • options: Optional cookie settings.

updateTokens(currentToken: string, refreshUrl: string, formatTokens: (rawTokens: any) => Tokens, options: CookieOptions) Updates tokens by calling a refresh API and updating the cookies.

  • currentToken: The current token to refresh.
  • refreshUrl: The API endpoint to refresh tokens.
  • formatTokens: Function to format the raw tokens from the API response.
  • options: Optional cookie settings.

CookieOptions

  • path: The path attribute of the cookie.
  • domain: The domain attribute of the cookie.
  • expires: The expiry time of the cookie (Date or seconds).
  • secure: Boolean indicating if the cookie should be sent over HTTPS.
  • sameSite: SameSite attribute for the cookie (Strict, Lax, None).