|
| 1 | +// TEMPLATE: This file will be copied to the Netlify functions directory when |
| 2 | +// running next-on-netlify/run.js |
| 3 | + |
| 4 | +const compat = require("next-aws-lambda") |
| 5 | +const { routes } = require("./routes.json") |
| 6 | + |
| 7 | +// We have to require all pages here so that Netlify's zip-it-and-ship-it |
| 8 | +// method will bundle them. That makes them available for our dynamic require |
| 9 | +// statement later. |
| 10 | +// We wrap this require in if(false) to make sure it is *not* executed when the |
| 11 | +// function runs. |
| 12 | +if (false) { |
| 13 | + require("./allPages") |
| 14 | +} |
| 15 | + |
| 16 | +// Look through all routes and check each regex against the request URL |
| 17 | +const getRoute = path => { |
| 18 | + route = routes.find(({ regex }) => { |
| 19 | + const re = new RegExp(regex, "i"); |
| 20 | + return re.test(path); |
| 21 | + }) |
| 22 | + |
| 23 | + // Return the route or the error page |
| 24 | + return route || { file: "pages/_error.js" } |
| 25 | +} |
| 26 | + |
| 27 | +exports.handler = (event, context, callback) => { |
| 28 | + // The following lines set event.path in development environments. |
| 29 | + // There is a difference in how Netlify handles redirects locally vs |
| 30 | + // production. Locally, event.path is set to the target of the redirect: |
| 31 | + // /.netlify/functions/nextRouter?_path=... |
| 32 | + // Deployed on Netlify, event.path is the source of the redirect: /posts/3 |
| 33 | + const isProduction = context.hasOwnProperty('awsRequestId') |
| 34 | + if(!isProduction) { |
| 35 | + event.path = event.queryStringParameters._path |
| 36 | + } |
| 37 | + |
| 38 | + // Get the request URL |
| 39 | + const { path } = event |
| 40 | + console.log("[request]", path) |
| 41 | + |
| 42 | + |
| 43 | + // Identify the file to render |
| 44 | + const { file } = getRoute(path) |
| 45 | + console.log("[render] ", file) |
| 46 | + |
| 47 | + |
| 48 | + // Load the page to render |
| 49 | + // Do not do this: const page = require(`./${file}`) |
| 50 | + // Otherwise, Netlify's zip-it-and-ship-it will attempt to bundle "./" |
| 51 | + // into the function's zip folder and the build will fail |
| 52 | + const pathToFile = `./${file}` |
| 53 | + const page = require(pathToFile) |
| 54 | + |
| 55 | + |
| 56 | + // Render the page |
| 57 | + compat(page)( |
| 58 | + { |
| 59 | + ...event, |
| 60 | + // Required. Otherwise, compat() will complain |
| 61 | + requestContext: {}, |
| 62 | + // Optional: Pass additional parameters to NextJS |
| 63 | + multiValueQueryStringParameters: {} |
| 64 | + }, |
| 65 | + context, |
| 66 | + callback |
| 67 | + ) |
| 68 | +}; |
0 commit comments