uWebSockets icon indicating copy to clipboard operation
uWebSockets copied to clipboard

[feature] Implement request.getCookie(name)

Open uasan opened this issue 5 years ago • 4 comments

Hey. You have implemented the request.getQuery(name) method with optional argument.

Often need a method request.getCookie(name). The best i could come up with in JS:

import { parse } from 'querystring';

parse(request.getHeader('cookie'), '; ')

But, parsing cookies in JS is not productive. It will be great if the method getCookie(name) appears in request object and is as efficient as getQuery(name). Thanks.

uasan avatar Nov 28 '20 21:11 uasan

this is what I use:

const getCookie=(req,name)=>(req.cookies??=req.getHeader('cookie')).match(getCookie[name]??=new RegExp(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`))?.[2]

// example
getCookie(req,'cookieName')

I tested this vs querystring.parse method, I show 370 nanoseconds for my getCookie and 1700 nanosec for querystring.parse, req.getHeader('cookie') takes up 210 ns of each

hst-m avatar Nov 28 '20 22:11 hst-m

querystring.parse - this method parses all cookies from the header line and decodeURIComponent() their values, I think this is the time difference

uasan avatar Nov 28 '20 22:11 uasan

This could make sense if getCookie is often used. It looks to be similar to getQuery - but there is no docs saying it should be URI decoded (some say it should be base64).

ghost avatar Nov 28 '20 23:11 ghost

no docs saying it should be URI decoded (some say it should be base64).

Yes, this is not part of the specification, this is the actual (historically) implementation for encoding special characters, but for many business logic, normal raw implementation - without decoding

uasan avatar Nov 28 '20 23:11 uasan