Express.JS: Attach cookie to statically served content

express.static not working
express serve html
add cookie express
create cookie express js
express set cookie
express cookie-session
cookieparser add cookie
using cookies express

I use Express.JS to serve static content:

express.use(express.static('./../'));

When index.html is served, I would like to send a cookie alongside the response indicating if the user is signed in or not. Normally one should use res.cookie() but I cannot see how to use it for statically served content.


Not sure why you need to do this, but you can place your own middleware before the static module.

The following quick hack should work:

function attach_cookie(url, cookie, value) {
  return function(req, res, next) {
    if (req.url == url) {
      res.cookie(cookie, value);
    }
    next();
  }
}

app.configure(function(){
  app.use(attach_cookie('/index.html', 'mycookie', 'value'));
  app.use(express.static(path.join(__dirname, 'public')));
});

The above inserts another function in the chain of middleware express uses before the static middleware. The new layer attaches the cookie to the response if the URL matches the specific one you are looking for -- and passes the response further down the chain.

Express cookie-session middleware, response-time · serve-favicon · serve-index · serve-static · session · timeout · vhost This is a Node.js module available through the npm registry. The middleware will automatically add a Set-Cookie header to the response if the contents of req.session were altered. Represents the session for the given request. To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The function signature is: The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static. For example, use the following code


Consider also the following approach:

  1. If your express is behind web-server you can serve static files without bothering express - it should be faster than via middle-ware. If you use nginx, this can help: Nginx Reverse Proxying to Node.js with Rewrite.

  2. Assuming that your static file has javascript in it, you can also set cookies directly on the client side only requesting from express the data you need for this cookie:

    document.cookie = "user_id=" + user_id;
    

    Flanagan's JS definitive guide (edition 6!) has an excellent coverage on how to use cookies in client-side javascript (in addition to being the best among JavaScript books :).

It can be a trivial advice, but I have seen the following flow (more than once): client sends API request (which has a cookie attached to it, obviously), server gets data from the cookie and serves the response completely built on the data contained in this cookie. All this instead of just quietly reading this cookie in the client. Basically client asks the server what it has in its own cookie.

In your scenario you need to request user_id/access_key only once and then always check the cookie in the client, going to the server only for the data that client doesn't already have, but storing and checking session state and, maybe, some compact data used in most pages (such as username, e.g.) in cookies locally (you can also cache data in local storage, to reduce the server load even further). In this case, express won't even know if a user accidentally refreshes the page (if you don't change URLs to reflect application state as well, of course, or only change #-part).

Express cookie-parser middleware, Parse Cookie header and populate req.cookies with an object keyed by the Given an object, this will iterate over the keys and call JSONCookie on each value,  To view cookies from your server, on the server console in a route, add the following code to that route. console.log('Cookies: ', req.cookies); Next time you send a request to this route, you will receive the following output. Cookies: { name: 'express' } Adding Cookies with Expiration Time. You can add cookies that expire.


As app.configure was removed since Express.js v4, I would like to do an update.

For Express.js versions > 4, to initialise my app by passing options inside the express.static(root, [options]) method, in which you can pass a Set-Cookie header in the property called setHeaders:

app.use(express.static(publicPath, {
  setHeaders: function (res, path, stat) {
    res.set('Set-Cookie', "myCookie=cookieValue;Path=/")
  }
}));

It is important to set Path=/ because otherwise express will create numerous duplicates of the cookie on the client side.

Serving Static Files in Express.js, While this tutorial has content that we believe is of great benefit to our community, we Express makes serving static files ridiculously easy! Let's put our Express server together, add the app.use line anywhere in between const To find out more about our use of cookies, please see our Privacy Policy. A simple app.js that serves up a static HTML file, probably referencing a JavaScript file also served by express. The HTML file that is served. The JavaScript file that the HTML file references. The version of Firefox that when you load the HTML file through the script in 1 does not load the JavaScript file.


Learning AngularJS: Learning AngularJS ePub _1, Consequently, Node.js provides a very nice interface to add and manage such as static files, routes, cookies, request parsing, and error handling. you will build a Node.js/Express web server and use it to serve static HTML, CSS, Create a file named server.js in the root of your project directory, place the contents from  method-override. Lets you use HTTP verbs such as PUT or DELETE in places where the client doesn’t support it. Install. This is a Node.js module available through the npm registry. Installation is done using the npm install command: $ npm install method-override API


Pro JavaScript Development: Coding, Capabilities, and Tooling, Now that we've seen the basics of writing Node.js applications in JavaScript, let's take a in Node.js to add support for common actions such as accessing cookie data, bodyParser()); // The express.static() middleware allows the contents of a This is perfect for // serving static files, such as JavaScript CSS, images, and  You can add middleware and HTTP method routes (such as get, put, post, and so on) to router just like an application. For more information, see Router. express.static(root, [options]) This is a built-in middleware function in Express. It serves static files and is based on serve-static.


Node.js for PHP Developers: Porting PHP to Node.js, Porting PHP to Node.js Daniel Howard initreq.njs'); exports.serve = function(​req, res) { var pre = {}; initreq. _COOKIE) { cookies.push(c + '=' + pre. res.end(​res.content); }); }); }); }); }); }); }; Now you should have an even better idea about If you need to tweak the Node.js web server to add pages, route URLs to specific​  Parse Cookie header and populate req.cookies with an object keyed by the cookie names. Optionally you may enable signed cookie support by passing a secret string, which assigns req.secret so it may be used by other middleware. $ npm install cookie-parser. var express = require ( 'express' ) var cookieParser = require ( 'cookie-parser' ) var app