Skip to content

Instantly share code, notes, and snippets.

@vwo-kb
Last active November 21, 2020 02:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vwo-kb/7e71e2deb836ae0ed10f60d0549dfb7d to your computer and use it in GitHub Desktop.
Save vwo-kb/7e71e2deb836ae0ed10f60d0549dfb7d to your computer and use it in GitHub Desktop.
Sync.js, Node.js Implementation
/**
* The following functions reads cookies created by VWO from request and syncs them back to client
*/
function syncCookies(request, response) {
let cookies = request.headers.cookie;
const responseHeaders = {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Origin": request.headers.origin ? request.headers.origin : "*"
};
if (!cookies) {
response.writeHead(200, responseHeaders);
response.end("1");
return;
}
cookies = cookies.split(";");
cookies.forEach(function(cookie) {
const cookieParts = cookie.trim().split("="),
name = cookieParts[0],
value = cookieParts[1];
if (name.search(/^(_vis_opt_|_vwo)/) !== -1) {
responseHeaders["Set-Cookie"] = responseHeaders["Set-Cookie"] || [];
// Expire any VWO cookies after 10 years.
// Set the cookie on root path so that it's accessible on all paths
// Set the domain to .<eTld+1>
responseHeaders["Set-Cookie"].push(`${name}=${value};path=/;domain=.<eTld+1>;expires=${new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000).toGMTString()}`);
// e.g. for a website example.abc.com eTld would be "com". So eTld+1 would be "abc.com".
// If you are not sure about what is the value in your case, you can contact the VWO support team.
// responseHeaders["Set-Cookie"].push(`${name}=${value};path=/;domain=.abc.com;expires=${new Date(Date.now() + 10 * 365 * 24 * 3600 * 1000).toGMTString()};`);
}
});
response.writeHead(200, responseHeaders);
response.end("1");
}
// If you are using express framework e.g., you can use the above code as follows
app.get('/sync', function(request, response) {
return syncCookies(request, response)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment