Skip to content

Commit

Permalink
feat: SSR - cookie removal on server-side + subsequent get()
Browse files Browse the repository at this point in the history
  • Loading branch information
rstoenescu committed Jun 14, 2018
1 parent c16afcb commit a2d12aa
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions src/plugins/cookies.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,9 @@ function read (string) {

function set (key, val, opts = {}, ssr) {
let time = opts.expires
const hasExpire = typeof opts.expires === 'number'

if (typeof opts.expires === 'number') {
if (hasExpire) {
time = new Date()
time.setMilliseconds(time.getMilliseconds() + opts.expires * 864e+5)
}
Expand All @@ -47,20 +48,37 @@ function set (key, val, opts = {}, ssr) {

const cookie = [
keyValue,
time ? '; expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
opts.path ? '; path=' + opts.path : '',
opts.domain ? '; domain=' + opts.domain : '',
opts.secure ? '; secure' : ''
time ? '; Expires=' + time.toUTCString() : '', // use expires attribute, max-age is not supported by IE
opts.path ? '; Path=' + opts.path : '',
opts.domain ? '; Domain=' + opts.domain : '',
opts.httpOnly ? '; HttpOnly' : '',
opts.secure ? '; Secure' : ''
].join('')

if (ssr) {
ssr.res.setHeader('Set-Cookie', cookie)

// make temporary update so future get()
// within same SSR timeframe would return the set value
ssr.req.headers.cookie = ssr.req.headers.cookie
? `${keyValue}; ${ssr.req.headers.cookie}`
: cookie

let all = ssr.req.headers.cookie || ''

if (hasExpire && opts.expires < 0) {
const val = get(key, ssr)
if (val !== undefined) {
all = all
.replace(`${key}=${val}; `, '')
.replace(`; ${key}=${val}`, '')
.replace(`${key}=${val}`, '')
}
}
else {
all = all
? `${keyValue}; ${all}`
: cookie
}

ssr.req.headers.cookie = all
}
else {
document.cookie = cookie
Expand Down

0 comments on commit a2d12aa

Please sign in to comment.