koa-prerender icon indicating copy to clipboard operation
koa-prerender copied to clipboard

Added support to stop next middleware processing upon options.stopNext=true

Open bibanul opened this issue 10 years ago • 7 comments

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.

bibanul avatar Dec 19 '14 19:12 bibanul

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

oroce avatar Dec 19 '14 20:12 oroce

Actually half of koa-prerender code is deciding to pre-render or not. Duplicating that code again outside of it is a huge waste.

bibanul avatar Dec 19 '14 21:12 bibanul

wouldn't it better to export the shouldPreRender function?

oroce avatar Dec 19 '14 21:12 oroce

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.

bibanul avatar Dec 19 '14 21:12 bibanul

Also this pull has a bugfix as well when no userAgent header is detected. Might want to consider that separate.

bibanul avatar Dec 19 '14 21:12 bibanul

setting header indeed sounds better. But I haven't seen anywhere setting header before yielding to next. (aren't there any downsides of this?)

oroce avatar Dec 19 '14 21:12 oroce

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

bibanul avatar Dec 19 '14 21:12 bibanul