Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Created October 13, 2019 13:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luandevpro/b4249cb6e1822c574fadb1877d55e0eb to your computer and use it in GitHub Desktop.
Save luandevpro/b4249cb6e1822c574fadb1877d55e0eb to your computer and use it in GitHub Desktop.
import { serialize } from 'cookie';
/**
* This sets `cookie` on `res` object
*/
const cookie = (res, name, value, options = {}) => {
const stringValue = typeof value === 'object' ? 'j:' + JSON.stringify(value) : String(value); // eslint-disable-line
if ('maxAge' in options) {
options.expires = new Date(Date.now() + options.maxAge); // eslint-disable-line
options.maxAge /= 1000; // eslint-disable-line
}
res.setHeader('Set-Cookie', serialize(name, String(stringValue), options));
};
/**
* Adds `cookie` function on `res.cookie` to set cookies for response
*/
const cookies = (handler) => (req, res) => {
res.cookie = (name, value, options) => cookie(res, name, value, options);
return handler(req, res);
};
export default cookies;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment