Skip to content

Instantly share code, notes, and snippets.

@codingmatty
Created February 21, 2019 13:41
Show Gist options
  • Save codingmatty/68a1e458ad4b405bb87113de51f3046b to your computer and use it in GitHub Desktop.
Save codingmatty/68a1e458ad4b405bb87113de51f3046b to your computer and use it in GitHub Desktop.
Next in Express example
const next = require('next');
const pathToRegexp = require('path-to-regexp');
const { parse } = require('url');
module.exports = async function registerNextApp(nextOptions) {
const nextApp = next(nextOptions);
const requestHandler = nextApp.getRequestHandler();
try {
await nextApp.prepare();
} catch (ex) {
console.error('NEXT ERROR', ex.stack);
process.exit(1);
}
// Return Express Router callback
return (req, res) => {
const parsedUrl = parse(req.url, true);
const { pathname, query } = parsedUrl;
if (pathname === '/a') {
nextApp.render(req, res, '/b', query)
} else if (pathname === '/b') {
nextApp.render(req, res, '/a', query)
} else {
requestHandler(req, res, parsedUrl)
}
};
};
async function setupExpress() {
const app = express();
// Register other endpoints
const clientHandler = await registerNext({ dev });
app.get('*', clientHandler); // allow next to handle remaining requests
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment