How to set session cookie using BrowserSync middleware?

I recently switched from an Express web application to a BrowserSync application for nodejs. Using Express, if I wanted to set a cookie, my configuration would look something like this:

var express = require('express'); var session = require('express-session'); var finalhandler = require('finalhandler'); var serveStatic = require('serve-static'), serve = serveStatic(__dirname); var app = express(); app.use(session({ // see https://github.com/expressjs/session secret: 'keyboard cat', resave: false, saveUninitialized: false })) .use(function(req, res, next) { res.cookie('myCookie', 'my cookie value'); var done = finalhandler(req, res); serve(req, res, done); }); app.listen(8080); 

My team started using BrowserSync (via the gulp task), and my configuration so far looks something like this:

 var gulp = require('gulp'), browserSync = require('browser-sync'), gulpLoadPlugins = require('gulp-load-plugins'), plugins = gulpLoadPlugins(); gulp.task('browser-sync', function() { browserSync({ server: { baseDir: "./", middleware: [ function(req, res, next) { res.cookie('myCookie', 'my cookie value'); next(); } ] }, port: 8080 }); }); 

However, the res object does not have a method called cookie. Is there something similar to session middleware for Expressjs that will work as BrowserSync middleware? Is there any other way to set cookies on a BrowserSync server?

+6
source share
2 answers

I had the same TypeError: res.cookie is not a function -error. The following configuration works for me.

  browsersync: { open: false, port: 8080, server: { baseDir: distDir, middleware: [ function(req, res, next) { res.setHeader('set-cookie', 'name=value'); next(); } ] } }, 
+3
source

Browser-sync uses connect , which has a slightly different API than an expression. This configuration worked for me to add a header and cookie to my responses using sync-sync:

  browsersync: { open: false, port: 8080, server: { baseDir: distDir, middleware: [ function(req, res, next) { res.setHeader('hello', 'world'); res.cookie('someCookie', 'cookieVal'); next(); } ] } }, 
-2
source

Source: https://habr.com/ru/post/979291/


All Articles