From a0930073535fdf9f31a4a3c140bd41d4e6801e64 Mon Sep 17 00:00:00 2001 From: Finn Woelm Date: Tue, 17 Nov 2020 13:06:55 +0800 Subject: [PATCH] Add support for res.redirect in API routes Copy over the files from the next-aws-lambda package and manually bundle them into our Netlify Functions. This gives us more flexibility to customize the compatibility layer between Netlify Functions and Next.js. For now, no changes have been made to the next-aws-lambda files and they have been copied as-is. next-aws-lambda source: https://github.com/serverless-nextjs/serverless-next.js/tree/master/packages/compat-layers/apigw-lambda-compat --- cypress/fixtures/pages/api/redirect.js | 6 ++++++ cypress/integration/default_spec.js | 8 ++++++++ lib/templates/createResponseObject.js | 4 ++++ 3 files changed, 18 insertions(+) create mode 100644 cypress/fixtures/pages/api/redirect.js diff --git a/cypress/fixtures/pages/api/redirect.js b/cypress/fixtures/pages/api/redirect.js new file mode 100644 index 0000000..9923aa3 --- /dev/null +++ b/cypress/fixtures/pages/api/redirect.js @@ -0,0 +1,6 @@ +export default async function preview(req, res) { + const { query } = req; + const { to } = query; + + res.redirect(`/shows/${to}`); +} diff --git a/cypress/integration/default_spec.js b/cypress/integration/default_spec.js index 3f9180a..4df81ee 100644 --- a/cypress/integration/default_spec.js +++ b/cypress/integration/default_spec.js @@ -526,6 +526,14 @@ describe("API endpoint", () => { ); }); }); + + it("redirects with res.redirect", () => { + cy.visit("/api/redirect?to=999"); + + cy.url().should("include", "/shows/999"); + cy.get("h1").should("contain", "Show #999"); + cy.get("p").should("contain", "Flash Gordon"); + }); }); describe("Preview Mode", () => { diff --git a/lib/templates/createResponseObject.js b/lib/templates/createResponseObject.js index 23335a4..78c0a28 100644 --- a/lib/templates/createResponseObject.js +++ b/lib/templates/createResponseObject.js @@ -24,6 +24,10 @@ const createResponseObject = ({ onResEnd }) => { res.writeHead = (status, headers) => { response.statusCode = status; if (headers) res.headers = Object.assign(res.headers, headers); + + // Return res object to allow for chaining + // Fixes: https://github.com/netlify/next-on-netlify/pull/74 + return res; }; res.write = (chunk) => { if (!response.body) {