Socket
Socket
Sign inDemoInstall

typescript-cookie

Package Overview
Dependencies
Maintainers
1
Versions
10
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

typescript-cookie

A simple, lightweight API for handling cookies in the browser


Version published
Weekly downloads
34K
decreased by-9.12%
Maintainers
1
Weekly downloads
 
Created
Source

A simple, lightweight TypeScript API for handling cookies.

Goals/Features

👉👉 If you're viewing this at https://github.com/typescript-cookie/typescript-cookie, you're reading the documentation for the master branch. View documentation for the latest release. 👈👈

Installation

NPM

$ npm i typescript-cookie

Basic Usage

Importing setter:

import { setCookie } from 'typescript-cookie'

All other functions not being used can be tree-shaken by a bundler.

Importing all:

import { getCookie, removeCookie, setCookie } from 'typescript-cookie'

Create a cookie, valid across the entire site:

setCookie('name', 'value')

Create a cookie that expires 7 days from now, valid across the entire site:

setCookie('name', 'value', { expires: 7 })

Create an expiring cookie, valid to the path of the current page:

setCookie('name', 'value', { expires: 7, path: '' })

Read cookie:

getCookie('name') // => 'value'
getCookie('nothing') // => undefined

Read all visible cookies:

getCookies() // => { name: 'value' }

Note: It is not possible to read a particular cookie by passing one of the cookie attributes (which may or may not have been used when writing the cookie in question):

getCookie('foo', { domain: 'sub.example.com' }) // `domain` won't have any effect...!

The cookie with the name foo will only be available on .get() if it's visible from where the code is called; the domain and/or path attribute will not have an effect when reading.

Delete cookie:

removeCookie('name')

Delete a cookie valid to the path of the current page:

setCookie('name', 'value', { path: '' })
removeCookie('name') // fail!
removeCookie('name', { path: '' }) // removed!

IMPORTANT! When deleting a cookie and you're not relying on the default attributes, you must pass the exact same path and domain attributes that were used to set the cookie:

removeCookie('name', { path: '', domain: '.yourdomain.com' })

Note: Removing a nonexistent cookie neither raises any exception nor returns any value.

Encoding

This project is RFC 6265 compliant. All special characters that are not allowed in the cookie-name or cookie-value are encoded with each one's UTF-8 Hex equivalent using percent-encoding.
The only character in cookie-name or cookie-value that is allowed and still encoded is the percent % character, it is escaped in order to interpret percent input as literal.
Please note that the default encoding/decoding strategy is meant to be interoperable only between cookies that are read/written by typescript-cookie. It's possible to override the default encoding/decoding strategy.

Note: According to RFC 6265, your cookies may get deleted if they are too big or there are too many cookies in the same domain, more details here.

expires

Define when the cookie will be removed. Value must be a Number which will be interpreted as days from time of creation or a Date instance. If omitted, the cookie becomes a session cookie.

To create a cookie that expires in less than a day, you can check the FAQ on the Wiki.

Default: Cookie is removed when the user closes the browser.

Examples:

setCookie('name', 'value', { expires: 365 })
getCookie('name') // => 'value'
removeCookie('name')

path

A String indicating the path where the cookie is visible.

Default: /

Examples:

setCookie('name', 'value', { path: '' })
getCookie('name') // => 'value'
removeCookie('name', { path: '' })

domain

A String indicating a valid domain where the cookie should be visible. The cookie will also be visible to all subdomains.

Default: Cookie is visible only to the domain or subdomain of the page where the cookie was created, except for Internet Explorer (see below).

Examples:

Assuming a cookie that is being created on site.com:

setCookie('name', 'value', { domain: 'subdomain.site.com' })
getCookie('name') // => undefined (need to read at 'subdomain.site.com')

secure

Either true or false, indicating if the cookie transmission requires a secure protocol (https).

Default: No secure protocol requirement.

Examples:

setCookie('name', 'value', { secure: true })
getCookie('name') // => 'value'
removeCookie('name')

sameSite

A String, allowing to control whether the browser is sending a cookie along with cross-site requests.

Default: not set.

Note that more recent browsers are making "Lax" the default value even without specifiying anything here.

Examples:

setCookie('name', 'value', { sameSite: 'strict' })
getCookie('name') // => 'value'
removeCookie('name')

Codec

Decode

All get methods that rely on a proper decoding to work, such as getCookies() and getCookie(), will run the given decoder for each cookie. The returned value will be used as the cookie value.

Example from reading one of the cookies that can only be decoded using the escape function:

import { DEFAULT_CODEC, getCookie, getCookies } from 'typescript-cookie'

document.cookie = 'escaped=%u5317'
document.cookie = 'default=%E5%8C%97'

const read: Decoder<string> = (value, name) => {
  if (name === 'escaped') {
    return unescape(value)
  }
  // Fall back to default for all other cookies
  return DEFAULT_CODEC.decodeValue(value, name)
}

getCookie('escaped', read) // => '北'
getCookie('default', read) // => '北'
getCookies(read) // => { escaped: '北', default: '北' }

Encode

Set a cookie with overriding the default encoding implementation:

import { setCookie } from 'typescript-cookie'

const write: Encoder<string> = (value) => value.toUpperCase()

setCookie('uppercased', 'foo', undefined, write) // => 'uppercased=FOO; path=/'

To ease migration while getting full TypeScript support there's a compat module that provides an api similar to js-cookie:

import Cookies from 'typescript-cookie'

Testing

$ npm test

Run tests continuously:

$ npm test -- --watch

Security

For vulnerability reports, send an e-mail to typescript-cookie at googlegroups dot com

Releasing

We are using release-it for automated releasing.

Start a dry run to see what would happen:

$ npm run release minor -- --dry-run

Do a real release (publishes both to npm as well as create a new release on GitHub):

$ npm run release minor

GitHub releases are created as a draft and need to be published manually! (This is so we are able to craft suitable release notes before publishing.)

Supporters

Many thanks to BrowserStack for providing unlimited browser testing free of cost.

Keywords

FAQs

Package last updated on 08 Sep 2021

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc