From c50e68fcf86aa1255a3601f87a074503f059ee17 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Fri, 2 Feb 2018 16:55:41 +0330 Subject: [PATCH] perf: improve cookie handling --- README.md | 6 +++--- lib/auth.js | 28 ++++++++-------------------- lib/defaults.js | 2 +- 3 files changed, 12 insertions(+), 24 deletions(-) diff --git a/README.md b/README.md index 6f8abae3d..618390c75 100644 --- a/README.md +++ b/README.md @@ -199,7 +199,7 @@ Default: ```js cookie: { name: 'token', - params: { + options: { path: '/' } } @@ -210,8 +210,8 @@ Using cookies is **required** for SSR requests to work with JWT tokens. It can be disabled by setting `cookie` to `false`. * **name** - Cookie name, -* **params** - Cookie params. - * `params.expires` can be used to speficy cookie lifetime in seconds. Default is session only. +* **options** - Cookie options. + * `options.expires` can be used to speficy cookie lifetime in seconds. Default is session only. ## License diff --git a/lib/auth.js b/lib/auth.js index e9b6e59d5..bc23e2eb4 100644 --- a/lib/auth.js +++ b/lib/auth.js @@ -1,5 +1,5 @@ -import Cookie from 'cookie' import Cookies from 'js-cookie' +import { parse as parseCookie } from 'cookie' import getProp from 'dotprop' import Vue from 'vue' @@ -153,29 +153,17 @@ export default class Auth { } } - setCookie (name, value, params = {}) { - if (!this.options.cookie) { + setCookie (name, value, options = {}) { + if (!this.options.cookie || !process.browser) { return } - const _params = Object.assign({}, this.options.cookie.params, params) + const _options = Object.assign({}, this.options.cookie.options, options) - if (!value) { - let date = new Date() - date.setDate(date.getDate() - 1) - _params.expires = date - } - - if (process.browser) { - Cookies.set(name, value, _params) + if (value) { + Cookies.set(name, value, _options) } else { - // Don't send duplicate token via Set-Cookie - if (!value) { - this.$res.setHeader( - 'Set-Cookie', - Cookie.serialize(name, value, _params) - ) - } + Cookies.remove(name, _options) } } @@ -184,7 +172,7 @@ export default class Auth { ? document.cookie : this.$req.headers.cookie - const cookies = Cookie.parse(cookieStr || '') || {} + const cookies = parseCookie(cookieStr || '') || {} return cookies[name] } diff --git a/lib/defaults.js b/lib/defaults.js index 737b22312..a0136fffc 100644 --- a/lib/defaults.js +++ b/lib/defaults.js @@ -17,7 +17,7 @@ module.exports = { }, cookie: { name: 'token', - params: { + options: { path: '/' } }