Giter Club home page Giter Club logo

nookies_setcookie's Introduction

nookies ๐Ÿช

Working npm version

A collection of cookie helpers for Next.js

Features

  • โœจ SSR support, for setter, parser and destroy
  • โš™๏ธ Custom Express server support
  • ๐Ÿชถ super light
  • ๐Ÿ›ก perfect for authentication

Setting and destroying cookies also works on server-side.

Quick start

yarn add nookies

You can play with the example code here.

ServerSide cookies

import nookies from 'nookies'

export default function Me() {
  return <div>My profile</div>
}

export async function getServerSideProps(ctx) {
  // Parse
  const cookies = nookies.get(ctx)

  // Set
  nookies.set(ctx, 'fromGetInitialProps', 'value', {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
  })

  // Destroy
  // nookies.destroy(ctx, 'cookieName')

  return { cookies }
}

Client-only Cookies

import { parseCookies, setCookie, destroyCookie } from 'nookies'

function handleClick() {
  // Simply omit context parameter.
  // Parse
  const cookies = parseCookies()
  console.log({ cookies })

  // Set
  setCookie(null, 'fromClient', 'value', {
    maxAge: 30 * 24 * 60 * 60,
    path: '/',
  })

  // Destroy
  // destroyCookie(null, 'cookieName')
}

export default function Me() {
  return <button onClick={handleClick}>Set Cookie</button>
}

Custom Express server cookies

const express = require('express');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
const { parseCookies, setCookie, destroyCookie } = require('nookies');

app.prepare()
    .then(() => {
        const server = express();

        server.get('/page', (req, res) => {

          // Notice how the request object is passed
          const parsedCookies = parseCookies({ req });

          // Notice how the response object is passed
          setCookie({ res }, 'fromServer', 'value', {
            maxAge: 30 * 24 * 60 * 60,
            path: '/page',
          });

          // destroyCookie({ res }, 'fromServer');

          return handle(req, res);
        });

    );

Reference

For client side usage, omit the ctx parameter. You can do so by setting it to an empty object ({}), null or undefined.

parseCookies(ctx, options) or nookies.get(ctx, options)

  • ctx: Next.js context || (Express request object)
  • options:
    • decode: a custom resolver function (default: decodeURIComponent)

setCookie(ctx, name, value, options) or nookies.set(ctx, name, value, options)

Don't forget to end your response on the server with res.send().

  • ctx: (Next.js context) || (Express request object)
  • name: cookie name
  • value: cookie value
  • options:
    • domain
    • encode
    • expires
    • httpOnly
    • maxAge
    • path
    • sameSite
    • secure

destroyCookie(ctx, name, options) or nookies.destroy(ctx, 'token', options)

Don't forget to end your response on the server with res.send(). This might be the reason your cookie isn't removed.

  • ctx: (Next.js context) || (Express response object)
  • name: cookie name
  • options:
    • domain
    • path

License

MIT

nookies_setcookie's People

Contributors

alirezamirsepassi avatar aminkhademian avatar aykutkardas avatar bukinoshita avatar dependabot[bot] avatar fabioruolo avatar gabsii avatar garth avatar hasparus avatar jforsaken avatar jvorcak avatar karlhorky avatar koprivajakub avatar lmachens avatar maticzav avatar mattisa avatar mkteh95 avatar omar-dulaimi avatar pesekviktor avatar renovate-bot avatar rexxars avatar szczepanbarszczowski avatar tomas2387 avatar vassbence avatar wootsbot avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.