Git Product home page Git Product logo

typescript-cookie's Introduction

TypeScript Cookie CI Status Maintainability Test Coverage npm

A simple, lightweight TypeScript API for handling cookies.

Goals/Features

Installation

NPM

npm i typescript-cookie

Basic Usage

Importing:

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

Functions not being used (that is imported) can be tree-shaken by a bundler.

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 additionally passing specific cookie attributes. A cookie will only be available if it's visible from where the code is called, visibility being controlled by path and domain used when setting a cookie.

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 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 an 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.

Cookie Attributes

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')
removeCookie('name')

path

A string indicating the path where the cookie is supposed to be visible.

Default: /

Examples:

setCookie('name', 'value', { path: '' })
getCookie('name')
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:

setCookie('name', 'value', { domain: 'subdomain.site.com' })
getCookie('name')
removeCookie('name', { domain: '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')
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')
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=/'

Testing

npm test

Run tests continuously:

npm test -- --watch

Releasing

Releasing should be done via the Release GitHub Actions workflow, so that published packages on npmjs.com have package provenance.

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.)

typescript-cookie's People

Contributors

axos88 avatar bunnymatic avatar carhartl avatar danielruf avatar dependabot[bot] avatar everdimension avatar fagnermartinsbrack avatar gazmull avatar github-actions[bot] avatar greenkeeper[bot] avatar greenkeeperio-bot avatar krinkle avatar kswedberg avatar luis-pato avatar lukasdrgon avatar mauriciabad avatar michaeldeboey avatar mrnice avatar nektro avatar nreynis avatar parikshit-hooda avatar prestonl avatar realityking avatar sahat avatar t0mtaylor avatar theodorejb avatar timse avatar tomsouthall avatar westy92 avatar xesau avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

typescript-cookie's Issues

Customizing getCookie return types

Is your feature request related to a problem? Please describe.
Would love to be able to add types to getCookie when I know what to expect

Describe the solution you'd like
Add generics to the signature: getCookie<KnownType>()

Describe alternatives you've considered
getCookie() as KnownType | undefined

Additional context
Not sure I'm up to it, but would be open to submitting a PR!

Cannot find module 'typescript-cookie' or its corresponding type declarations.

Describe the bug
Cannot find module 'typescript-cookie' or its corresponding type declarations.

To Reproduce
1.- Install the latest release v1.0.0 via: npm i typescript-cookie
2.- Import the getCookie as the documentation says
3.- VSC display error about missing library or type declarations

Expected behavior
Expect no error on a TS library about missing types. Maybe I'm doing something wrong.

Screenshots
image

Desktop (please complete the following information):

  • OS: Windows 10

Prefer `{"exports": ".

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Smartphone (please complete the following information):

  • Device: [e.g. iPhone6]
  • OS: [e.g. iOS8.1]
  • Browser [e.g. stock browser, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Cannot import library when using Jest

Describe the bug

The library works great when running my application, but fails to import when running tests with Jest. Tests fails with the error message:

Cannot find module 'typescript-cookie' from 'path/to/my/file.tsx'

I found others with the same problem on this Stack Overflow post leading me to believe it's an issue with typescript-cookie.

Additional context

I'm using the library within a project created with create-react-app. In the above linked Stack Overflow post, the other user had the same error within a project created with "VITE + TS."

Error TS7016 - Could not find a declaration file

Describe the bug
If you use the new nodeResolution bundler option introduced in TypeScript 5.0 tsc will not find the declaration file for its imports and throw the following error:

error TS7016: Could not find a declaration file for module 'typescript-cookie'. 'D:/Test/.yarn/cache/typescript-cookie-npm-1.0.4-67c5369c2e-9fb4c76bd2.zip/node_modules/typescript-cookie/dist/typescript-cookie.mjs' implicitly has an 'any' type.
  There are types at 'D:/Test/.yarn/cache/typescript-cookie-npm-1.0.4-67c5369c2e-9fb4c76bd2.zip/node_modules/typescript-cookie/dist/src/index.d.ts', but this result could not be resolved when respecting package.json "exports". The 'typescript-cookie' library may need to update its package.json or typings.

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

To Reproduce
Steps to reproduce the behavior:

  1. Add "typescript-cookie": "^1.0.4" and "typescript": "^5.0.2" to package.json
  2. Set "moduleResolution": "bundler" in tsconfig.json
  3. Import something from 'typescript-cookie': import { setCookie } from 'typescript-cookie';
  4. Compile the file with tsc

Expected behavior
I expected tsc to find the type declaration file for 'typescript-cookie'.

Desktop (please complete the following information):

  • OS: Microsoft Windows 10 Pro 10.0.19043 Build 19043
  • Version: typescript-cookie 1.0.4

Module not found: Error: Package path . is not exported from package

Describe the bug

An error Module not found: Error: Package path . is not exported from package /Users/ishotihadus/test/node_modules/typescript-cookie (see exports field in /Users/ishotihadus/test/node_modules/typescript-cookie/package.json) occurs when building with webpack in some cases.

I think this is caused by package.json:

"exports": {
    ".": {
      "import": "./dist/typescript-cookie.mjs",
    },
    "./package.json": "./package.json"
  },

I think there are two candidates to solve this problem.

"exports": {
    ".": {
      "import": "./dist/typescript-cookie.mjs",
      "require": "./dist/typescript-cookie.mjs",
    },
    "./package.json": "./package.json"
  },

or

"exports": {
    ".": "./dist/typescript-cookie.mjs",
    "./package.json": "./package.json"
  },

If this restriction to import is not necessary, I think the above solutions are helpful.

To Reproduce

webpack.config.ts

import * as webpack from 'webpack';

const config: (env: any) => webpack.Configuration = (env) => {
  return {
    mode: 'production',
    entry: { 'test.js': './test.ts' },
    module: {
      rules: [
        {
          test: /\.(ts|tsx)$/i,
          exclude: /(^|\/)node_modules\//,
          use: [{ loader: 'ts-loader' }]
        }
      ]
    }
  };
};

export default config;

tsconfig.json

{
  "compilerOptions": {
    "target": "ESNext",
    "module": "commonjs",
    "strict": true,
  }
}

test.ts

import { setCookie } from 'typescript-cookie';

setCookie('hoge', 'piyio', { expires: 60, secure: true, domain: 'example.com' });

Expected behavior

Webpack can build without an error.

Dissolve monolithic api object

With modules we can solve this with exports, no need to construct an object any longer. Will also allow for better tree-shakability, when for instance only writing cookies (?)

export { get, set, remove }

and

import * as Cookies from 'ts-cookie'

How to solve withConverter(), withAttributes() though?

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.