Coder Social home page Coder Social logo

express-cache-controller's Introduction

express-cache-controller

A simple and lightweight module for managing cache control headers from within your application. It also tries to provide a simple set of rules for common use cases such as setting 'max-age=0' when 'no-cache' is present by default.

Example

Configuring noCache easily:

app.use(cacheControl({
  noCache: true
}));

Creates a cache-control header of no-cache, max-age=0

Usage

To start using cacheControl, just use the middleware in your application:

app.use(cacheControl());

Default Cache Headers

When initialising the middleware you can set default options when you use it in your application:

app.use(cacheControl({
    maxAge: 5
}));

Overriding Defaults

Just set the cacheControl property of the response object after the cacheControl() middleware is loaded:

app.use(cacheControl({ maxAge: 60 }));
app.get('/', function (req, res, next){
  res.cacheControl = {
      maxAge: 30
  };

  res.send('hai');
});

This is useful in error conditions where you can setup cache headers before and after a request is processed:

app.use(cacheControl({ maxAge: 60} ));
app.get('/', function (req, res, next) {
  next(Error('BOOM!'));
});
app.use(function (err, req, res, next) {
  res.cacheControl = {
      maxAge: 5
  };

  res.status(500).send('oh no!');
});

Options

Name Value Description
private Boolean Adds 'private' flag, overrides 'public' option
public Boolean Adds 'public' flag
noStore Boolean Adds 'no-store' flag and includes noCache
noCache Boolean Adds 'no-cache' flag, sets maxAge to 0 and removes sMaxAge, staleIfError and staleWhileRevalidate
noTransform Boolean Adds 'no-transform' flag
mustRevalidate Boolean Adds 'must-revalidate' flag and removes staleIfError and staleWhileRevalidate
staleIfError Number Adds 'stale-if-error=%d' flag
staleWhileRevalidate Number Adds 'stale-while-revalidate=%d' flag
maxAge Number Adds 'max-age=%d' flag
sMaxAge Number Adds 's-maxage=%d' flag

express-cache-controller's People

Contributors

greenkeeperio-bot avatar maksimovicdanijel avatar mousius avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

express-cache-controller's Issues

Middleware unable to be used by Express router

Was trying to use this module to apply different default cache control settings on two Express routers mounted on an app, and it seem this use case is not supported (perhaps because of (odd?) way that the modules exposes a function the returns a named function?)

My code looked like:

const cacheControl = require('express-cache-controller');
...
apiRouter.use(cacheControl({ [options] });
...
mainRouter.use(cacheControl({ [options] });

This did not work and there was not any sort of error triggered. My routers just simply did not apply the correct headers.

I tried other alternatives like:

const cacheControlInit = require('express-cache-controller');
...
apiRouter.use(cacheControlInit ({ [options] });
...
mainRouter.use(cacheControlInit ({ [options] });

and:

require('express-cache-controller')({ [options] });
...
apiRouter.use(cacheControl);
...
mainRouter.use(cacheControl);

but wasn't able to get to work until finally just doing:

const cacheControl = require('express-cache-controller');
...
app.use(cacheControl({ [options] });

Figured I would open an issue, as it would be unexpected behavior IMO middleware to not work on a router.

I also think it would be extremely helpful to include information on how to properly require the module in your documentation. I saw there was an old closed issue about this, but the documentation doesn't show this. It would have probably saved some time in me fiddling around with various approaches to including this module.

How to require this controller?

I had downloaded this package, and the following code is my configuration :

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cacheControl = require('..');
var indexRouter = require('./routes/index');
var register = require('./routes/register');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(cacheControl({
  noCache: true
}));

app.use('/', indexRouter);
app.use('/register', register);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and the console had showed

   app.use(cacheControl({
        ^

TypeError: cacheControl is not a function

Caching directives conflict with (override) express.static

In working with the cache control middleware, it seems that it does not play nicely with express.static middleware. If this middleware is used before the static middleware, the cache expiry settings from express-cache-controller will override any expiry settings provided in static. When including this middleware after static things seem to work correctly.

It might be useful to at least include this in documentation so users would be aware of this interaction.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.