koa-prerender
koa-prerender copied to clipboard
Added support to stop next middleware processing upon options.stopNext=true
Useful when same KOA website serves regular requests and also handles the pre-rendering interception and return right after the content is obtained from PhantomJS. Example: your Angular app hits your API KOA server. You also want to intercept the prerendering request in same stack and return right after. This allows you to not keep a stand alone stack just to mount koa-prerender alone.
I think this shouldn't be in koa-prerender
, but conditionally intercepting using middlewares.
var koa = require('koa');
var router = require('koa-route');
var prerender = require('koa-prerender');
var app = koa();
app.use(prerender());
app.use(function *(next) {
// if the request is text/html, it has been already handled by koa-prerender
if (this.is('text/html')) {
return;
}
yield next;
});
app.use(router.get('/', function *() {
this.body = 'this is the /';
}));
app.listen(3000);
Or see conditional-middleware example: https://github.com/koajs/examples/tree/master/conditional-middleware
Actually half of koa-prerender code is deciding to pre-render or not. Duplicating that code again outside of it is a huge waste.
wouldn't it better to export the shouldPreRender
function?
Actually I would have preferred some sort of flag that says if it was prerendered. The header is set after yielding next sadly :). You can try to set the header before yielding hence once can check and/or exposing a wasPrerendered flag that reads same value and/or as you suggested exporting shouldPrerender.
Also this pull has a bugfix as well when no userAgent header is detected. Might want to consider that separate.
setting header indeed sounds better. But I haven't seen anywhere setting header before yielding to next. (aren't there any downsides of this?)
I think each middleware does its job on setting headers that they need. I set the global cache at the beginning before any middleware kicks in for example. koa-cors kicks in before other middleware and all they do is setting a set of headers then yielding next. tbh, there should be a property that is exported to indicate if content was prerendered so actual code can exit. in my case the middleware after pre-render is koa-jwt and it was returning me the prerendered content but with 401 header :D