Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a session cookie via BrowserSync middleware?

I've recently moved from an Express web app to a BrowserSync app for nodejs. Using Express, if I wanted to set a cookie, my config 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 has started using BrowserSync (via a gulp task), and my config, 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 named "cookie". Is there something similar to the session middleware for Expressjs that will work as BrowserSync middleware? Is there another way to set cookies in a BrowserSync server?

like image 232
Troy Avatar asked Dec 08 '14 20:12

Troy


1 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();
        }
      ]
    }
  },
like image 141
Peter Ahlers Avatar answered Oct 11 '22 22:10

Peter Ahlers