Last active
November 25, 2017 15:14
-
-
Save maximilianschmitt/3a14dffd6645dd4529f6 to your computer and use it in GitHub Desktop.
Redirects on the server with react-router, express and iniquest
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.use(function(req, res, next) { | |
const router = Router.create({ | |
routes, | |
location: req.path | |
}); | |
router.run(function(Handler, state) { | |
router.transitionTo = function() { | |
const redirectUrl = router.makeHref.apply(router, arguments); | |
return Promise.reject({ reason: 'redirect', redirectUrl }); | |
}; | |
iniquest.run(state, req, router).then(initialState => { | |
const html = React.renderToString(<Handler initialState={initialState} />); | |
res.send(render(html, initialState)); | |
}).catch(err => { | |
if (err && err.reason === 'redirect') { | |
return res.redirect(err.redirectUrl); | |
} | |
next(err); | |
}); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// sample component | |
Users.prepareForRequest = function(req, router) { | |
if (req.method === 'POST') { | |
return router.transitionTo('some-url', { some: 'param' }); | |
} | |
return RSVP.hash({ | |
users: users.all() | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment