Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to use ES6 generators with Hapi.js <3
import co from 'co'
// Generator controller,
// this.models refers to Sequelize models added with server.bind()
function* loginController(request) {
let user = yield this.models.User.find({
where: {
if (!user)
yield Promise.reject(Boom.notFound('USER_NOT_FOUND'));
return user.toJSON();
// Wraps generator so it can be used in Hapi responses
function wrapGen(generator) {
let handler = co.wrap(generator);
return function(request, reply) {
handler.bind(this)(request, reply)
// Here's the most typical Hapi.js route
method: 'POST',
path: '/auth/login',
handler: wrapGen(loginController)
Copy link

danielyogel commented Nov 23, 2015

@nackjicholson This is very nice, is it working as expected?

Copy link

ebertmi commented Mar 20, 2016

With newer co versions the wrapping is even easier.

Just use

import co from 'co';

// Wraps generator so it can be used in Hapi Route Handlers
function generoute(generator) {
  return co.wrap(generator);

export default generoute;

This allows to use a generator handler with request and reply.

function* myHandler (request, reply) {
  try {
    let user =  yield DB.getUser(;
  } catch (e) {
       customErrorMessage: 'All your base are belong to us!'

This allows to set the HTTP response codes, etc.

Copy link

noveogroup-amorgunov commented Mar 24, 2017

I wrote small plugin for this: noveogroup-amorgunov/hapi-generoutify

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment