Created
February 21, 2019 13:41
-
-
Save codingmatty/68a1e458ad4b405bb87113de51f3046b to your computer and use it in GitHub Desktop.
Next in Express example
This file contains 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
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) | |
} | |
}; | |
}; |
This file contains 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
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