Skip to content
Fix Code Error

Trouble with Next js + Express deployment using Zeit Now

April 16, 2021 by Code Error
Posted By: Anonymous

I have written a simple SSR Next js web page with an express server attached to handle some email functionality I have attached to a contact form.

I have tried deploying to now and, whilst the terminal says I have done so successfully, I get a 502 error when I make network requests to my express server.

now.json:

{
  "version": 2,
  "builds": [
    {"src": "package.json", "use": "@now/next"},
    {"src": "/server/index.js", "use": "@now/node-server"}
  ],
  "routes": [{"src": "/api/contact", "dest": "/server/index.js"}]
}

next.config.js:

const { PHASE_PRODUCTION_SERVER } =
  process.env.NODE_ENV === 'development'
    ? {} // We're never in "production server" phase when in development mode
    : !process.env.NOW_REGION 
      ? require('next/constants') // Get values from `next` package when building locally
      : require('next-server/constants'); // Get values from `next-server` package when building on now v2

module.exports = (phase, { defaultConfig }) => {
  if (phase === PHASE_PRODUCTION_SERVER) {
    // Config used to run in production.
    return {};
  }

  const withSass = require('@zeit/next-sass');

  return withSass();
};

I had a look at now-examples but unfortunately this particular combination of libraries isn’t represented and I’m not skilled enough a programmer to understand the inner workings of them myself.

Any help would be greatly appreciated. My server code is

INDEX.JS

const express = require('express');
const next = require('next');
const bodyParser = require('body-parser');

const mailer = require('./mailer/mailer.js');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev })
const handle = app.getRequestHandler()

app.prepare().then(() => {
  const server = express();

  server.use(bodyParser.json());

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.post('/api/contact', (req, res) => {
    const { firstName, lastName, phoneNumber, emailAddress, messageText } = req.body

    mailer.send( firstName, lastName, phoneNumber, emailAddress, messageText ).then(() => {
      console.log(`Sent the message "${messageText}" from <${firstName}> ${emailAddress}.`);
      res.status(200);
      res.send('success')
    }).catch((error) => {
      console.log(`Failed to send the message "${messageText}" from <${firstName}> ${emailAddress} with the error ${error && error.message}`);
      res.status(400);
      res.send('failure')
    })
  });

  server.listen( (process.env.PORT || 3000) , (err) => {
    if (err) throw err
    console.log('> Read on http://localhost:3000')
  });

});

The rest of my next.js app is very straightforward.

Logs:

2019-03-19T11:01:49.575Z  [11:01:49] Compiling client
2019-03-19T11:01:49.598Z  [11:01:49] Compiling server
2019-03-19T11:01:52.602Z  [11:01:52] Compiled server in 3s
2019-03-19T11:02:00.177Z  info [email protected]: The platform "linux" is incompatible with this module.
2019-03-19T11:02:00.177Z  info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
2019-03-19T11:02:00.183Z  [3/4] Linking dependencies...
2019-03-19T11:02:00.199Z  warning "@zeit/next-sass > [email protected]" has unmet peer dependency "[email protected]^2.0.0 || >= 3.0.0-rc.0 || ^3.0.0".
2019-03-19T11:02:00.200Z  warning "@zeit/next-sass > @zeit/next-css > [email protected]" has unmet peer dependency "[email protected]^4.0.0".
                          warning "@zeit/next-sass > @zeit/next-css > [email protected]" has unmet peer dependency "[email protected]^4.4.0".
2019-03-19T11:02:00.208Z  warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^4.3.0".
2019-03-19T11:02:00.209Z  warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^4.0.0".
                          warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^3.0.0 || ^4.0.0".
2019-03-19T11:02:00.209Z  warning " > [email protected]" has unmet peer dependency "[email protected]^15.6.0".
2019-03-19T11:02:02.880Z  [11:02:02] Compiled client in 13s
2019-03-19T11:02:03.396Z  compiling entrypoint with ncc...
2019-03-19T11:02:06.428Z  [4/4] Building fresh packages...
2019-03-19T11:02:08.530Z  success Saved lockfile.
2019-03-19T11:02:08.538Z  Done in 28.73s.
2019-03-19T11:02:08.806Z  yarn cache v1.13.0
2019-03-19T11:02:11.332Z  success Cleared cache.
2019-03-19T11:02:11.332Z  Done in 2.54s.
2019-03-19T11:02:11.341Z  running user script...
2019-03-19T11:02:11.342Z  running "yarn run now-build"
2019-03-19T11:02:11.592Z  yarn run v1.13.0
2019-03-19T11:02:11.670Z  $ NODE_OPTIONS=--max_old_space_size=3000 next build --lambdas
2019-03-19T11:02:13.254Z  [11:02:13] Compiling client
2019-03-19T11:02:15.907Z  ncc: Module directory "/tmp/6b60c2d/user/node_modules/chokidar/lib" attempted to require "fsevents" but could not be resolved, assuming external.
2019-03-19T11:02:31.586Z  downloading user files...
2019-03-19T11:02:31.679Z  installing dependencies for user's code...
2019-03-19T11:02:31.680Z  installing to /tmp/84eaca5/user/server
2019-03-19T11:02:35.826Z  Browser assets sizes after gzip:

                             19.3 kB  .next/static/0rX3****/pages/_app.js
                             12.3 kB  .next/static/0rX3****/pages/_error.js
                             1.04 kB  .next/static/0rX3****/pages/components/about/About.js
                             6.64 kB  .next/static/0rX3****/pages/components/backtotopbutton/BackToTopButton.js
                             1.14 kB  .next/static/0rX3****/pages/components/bookingcard/BookingCard.js
                               323 B  .next/static/0rX3****/pages/components/bookingcard/components/calendlywidget/CalendlyWidget.js
                             8.31 kB  .next/static/0rX3****/pages/components/contactcard/ContactCard.js
                             8.26 kB  .next/static/0rX3****/pages/components/contactcard/components/contactform/ContactForm.js
                             6.55 kB  .next/static/0rX3****/pages/components/landingcard/LandingCard.js
                             7.09 kB  .next/static/0rX3****/pages/components/mapview/MapContainer.js
                             6.81 kB  .next/static/0rX3****/pages/components/mapview/components/mapview/MapView.js
                             8.49 kB  .next/static/0rX3****/pages/components/navbar/NavBar.js
                             7.91 kB  .next/static/0rX3****/pages/components/navbar/components/burgermenu/BurgerMenu.js
                               478 B  .next/static/0rX3****/pages/components/servicescard/ServicesCard.js
                             25.7 kB  .next/static/0rX3****/pages/index.js
                             56.2 kB  .next/static/chunks/commons.ebad****.js
                               154 B  .next/static/chunks/styles.49ee****.js
                             3.01 kB  .next/static/css/styles.ee9ce638.chunk.css
                             23.4 kB  .next/static/runtime/main-44b4****.js
                               737 B  .next/static/runtime/webpack-8917****.js

2019-03-19T11:02:35.830Z  [11:02:35] Compiled client in 23s
2019-03-19T11:02:35.854Z  [11:02:35] Compiling server
2019-03-19T11:02:36.469Z  npm WARN
2019-03-19T11:02:36.470Z   [email protected] No repository field.
2019-03-19T11:02:36.470Z  npm WARN optional SKIPPING OPTIONAL DEPENDENCY: [email protected] (node_modules/fsevents):
                          npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
2019-03-19T11:02:36.470Z
2019-03-19T11:02:36.470Z  up to date in 4.427s
2019-03-19T11:02:36.657Z  npm
2019-03-19T11:02:36.658Z
2019-03-19T11:02:36.658Z  WARN using --force
2019-03-19T11:02:36.658Z   I sure hope you know what you are doing.
2019-03-19T11:02:36.773Z  writing ncc package.json...
2019-03-19T11:02:36.773Z  installing dependencies for ncc...
2019-03-19T11:02:36.773Z  installing to /tmp/84eaca5/ncc
2019-03-19T11:02:36.938Z  yarn install v1.13.0
2019-03-19T11:02:36.962Z  [1/4] Resolving packages...
2019-03-19T11:02:36.983Z  success Already up-to-date.
2019-03-19T11:02:36.985Z  Done in 0.05s.
2019-03-19T11:02:37.152Z  yarn cache v1.13.0
2019-03-19T11:02:37.173Z  success Cleared cache.
2019-03-19T11:02:37.173Z  Done in 0.03s.
2019-03-19T11:02:55.631Z  [11:02:55] Compiled server in 20s
2019-03-19T11:02:55.737Z  Done in 44.15s.
2019-03-19T11:02:55.743Z  running npm install --production...
2019-03-19T11:02:55.743Z  installing to /tmp/77afa5cd
2019-03-19T11:02:55.994Z  yarn install v1.13.0
2019-03-19T11:02:56.142Z  [1/4] Resolving packages...
2019-03-19T11:02:57.021Z  [2/4] Fetching packages...
2019-03-19T11:03:10.921Z  info [email protected]: The platform "linux" is incompatible with this module.
2019-03-19T11:03:10.921Z  info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
2019-03-19T11:03:10.931Z  [3/4] Linking dependencies...
2019-03-19T11:03:10.939Z  warning "@zeit/next-sass > [email protected]" has unmet peer dependency "[email protected]^2.0.0 || >= 3.0.0-rc.0 || ^3.0.0".
2019-03-19T11:03:10.940Z  warning "@zeit/next-sass > @zeit/next-css > [email protected]" has unmet peer dependency "[email protected]^4.0.0".
                          warning "@zeit/next-sass > @zeit/next-css > [email protected]" has unmet peer dependency "[email protected]^4.4.0".
2019-03-19T11:03:10.949Z  warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^4.0.0".
2019-03-19T11:03:10.950Z  warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^4.3.0".
2019-03-19T11:03:10.950Z  warning "next-optimized-images > [email protected]" has unmet peer dependency "[email protected]^3.0.0 || ^4.0.0".
2019-03-19T11:03:10.950Z  warning " > [email protected]" has unmet peer dependency "[email protected]^15.6.0".
2019-03-19T11:03:13.518Z  [4/4] Building fresh packages...
2019-03-19T11:03:13.567Z  Done in 17.58s.
2019-03-19T11:03:13.834Z  yarn cache v1.13.0
2019-03-19T11:03:16.398Z  success Cleared cache.
2019-03-19T11:03:16.399Z  Done in 2.57s.
2019-03-19T11:03:16.666Z  preparing lambda files...
2019-03-19T11:03:16.840Z  Creating lambda for page: "components/about/About.js"...
2019-03-19T11:03:16.841Z  Creating lambda for page: "components/backtotopbutton/BackToTopButton.js"...
2019-03-19T11:03:16.841Z  Creating lambda for page: "components/bookingcard/BookingCard.js"...
2019-03-19T11:03:16.842Z  Creating lambda for page: "components/bookingcard/components/calendlywidget/CalendlyWidget.js"...
2019-03-19T11:03:16.842Z  Creating lambda for page: "components/contactcard/components/contactform/ContactForm.js"...
2019-03-19T11:03:16.843Z  Creating lambda for page: "components/contactcard/ContactCard.js"...
2019-03-19T11:03:16.843Z  Creating lambda for page: "components/landingcard/LandingCard.js"...
2019-03-19T11:03:16.844Z  Creating lambda for page: "components/mapview/components/mapview/MapView.js"...
2019-03-19T11:03:16.844Z  Creating lambda for page: "components/mapview/MapContainer.js"...
2019-03-19T11:03:16.845Z  Creating lambda for page: "components/navbar/components/burgermenu/BurgerMenu.js"...
2019-03-19T11:03:16.845Z  Creating lambda for page: "components/navbar/NavBar.js"...
2019-03-19T11:03:16.845Z  Creating lambda for page: "components/servicescard/ServicesCard.js"...
2019-03-19T11:03:16.846Z  Creating lambda for page: "index.js"...
2019-03-19T11:03:17.851Z  Created lambda for page: "components/about/About.js"
2019-03-19T11:03:18.495Z  Created lambda for page: "components/backtotopbutton/BackToTopButton.js"
2019-03-19T11:03:19.099Z  Created lambda for page: "components/bookingcard/BookingCard.js"
2019-03-19T11:03:19.668Z  Created lambda for page: "components/bookingcard/components/calendlywidget/CalendlyWidget.js"
2019-03-19T11:03:20.169Z  Created lambda for page: "components/contactcard/components/contactform/ContactForm.js"
2019-03-19T11:03:20.923Z  Created lambda for page: "components/contactcard/ContactCard.js"
2019-03-19T11:03:21.383Z  Created lambda for page: "components/landingcard/LandingCard.js"
2019-03-19T11:03:22.061Z  Created lambda for page: "components/mapview/components/mapview/MapView.js"
2019-03-19T11:03:22.759Z  Created lambda for page: "components/mapview/MapContainer.js"
2019-03-19T11:03:23.336Z  Created lambda for page: "components/navbar/components/burgermenu/BurgerMenu.js"
2019-03-19T11:03:23.772Z  Created lambda for page: "components/navbar/NavBar.js"
2019-03-19T11:03:24.416Z  Created lambda for page: "components/servicescard/ServicesCard.js"
2019-03-19T11:03:24.988Z  Created lambda for page: "index.js"
2019-03-19T11:03:28.817Z  preparing cache ...
2019-03-19T23:29:10.708Z  REPORT RequestId: 2b7c115d-9d46-4eef-a2d9-4788ed22116a        Duration: 130.73 ms     Billed Duration: 200 ms         Memory Size: 3008 MB    Max Memory Used: 89 MB

Solution

you will have to use lambdas with the following now.json

{
    "version": 2,
    "builds": [
        { "src": "package.json", "use": "@now/next" },
        { "src": "lambda_file.js", "use": "@now/node"}
    ],
    "routes": [
        { "src": "api_route", "dest": "lambda_file.js"}
    ]
}
Answered By: Anonymous

Related Articles

  • Automapper Aftermap alternative for Nested Mapping
  • How to solve Internal Server Error in Next.Js?
  • How to set up webpack-hot-middleware in an express app?
  • Problems Installing CRA & NextJS from NPM…
  • getting text input from a form in react.js using Refs
  • Firebase deployng Sapper app as cloud function failed
  • Automapper map to tuple which first element is list…
  • Interrupt an earlier timeout event in Simpy
  • How to change the integrated terminal in visual…
  • Most efficient method to groupby on an array of objects
  • Convert python script to airflow dag
  • Svelte application not working on android version…
  • Creating nested dicts with dynamic key and values
  • Worker Script Failing to Load for Vue Webpack Built App
  • Nuxt Hot reloading for new components Is not working
  • Vuejs - How to use a single form to add and edit
  • react-table has a issue with rendering in next.js
  • Ember.js - CRUD scenarios - Specifying View from…
  • Resizing an image in an HTML5 canvas
  • Why am I getting an error while concatenating 2 strings?
  • Webpack dev server for vue-cli: Error spawn EACCES
  • Passport.js in Next.js app not saving user across…
  • Simulating a system of resource with…
  • laravel vuejs/axios put request Formdata is empty
  • How to run Next Js application build (out) directory?
  • How to use module.exports in Next.js
  • Aurelia, navigate is not updating viewport
  • ExpressJS How to structure an application?
  • disable vue-cli webpack encoding image base64
  • TypeError: Cannot read property 'webpackJsonp' of undefined
  • Argument 1 passed to…
  • webpack-dev-server npm run dev throwing TypeError:…
  • Copy a file in a sane, safe and efficient way
  • React NextJS app, installed webpack, then removed…
  • Run nuxt on https locally – problem with nuxt.config.js
  • Adding Dynamic Input Fields With VueJs
  • Correctly configure webpack-dev-middleware with…
  • dotenv values not loaded in nextjs
  • Import alias svelte component in typescript svelte
  • Vue cli 3 display info from the package.json
  • Server side load a global component with Next.js in React
  • next-i18next not support assetPrefix url?
  • firebase.initializeApp can't find the API key in my…
  • Module not found: Can't resolve 'fs' in…
  • How to map lists without overwriting values
  • Why is my Shopify App built with Next.js (React) so…
  • Build error occurred ReferenceError: describe is not…
  • .bind no longer working after upgrading to new…
  • How to config Ant Design in Next.js with custom…
  • Use of PUT vs PATCH methods in REST API real life scenarios
  • Adding a UserCreationForm to html in Django
  • AureliaJS - replacing looped elements with a…
  • How to build next.js production?
  • Can't install via pip because of egg_info error
  • Version vs build in Xcode
  • Spring Boot - Cannot determine embedded database…
  • Specifying java version in maven - differences…
  • Nextjs and Express as middle ware. How do I set…
  • Pass environment variable into a Vue App at runtime
  • Docker compose build time args from file
  • commandButton/commandLink/ajax action/listener…
  • why req.body is empty and req.files undefined
  • Webpack build error
  • webpack-hot-middleware throws error on HMR update -…
  • Node.js/NodeMailer/Express/Outlook smtp host -…
  • Can't upload files with Apollo-client GraphQL in…
  • Next.js pass NODE_ENV to client
  • Sapper/Svelte rollup/plugin-json giving error with stripejs
  • npm run dev command does not work on vuejs'…
  • Add custom Netlify CMS widget to Gatsby starter Yellowcake
  • error LNK2005: ✘✘✘ already defined in…
  • Understanding PrimeFaces process/update and JSF…
  • Backbone.js app not rendering view
  • Neither BindingResult nor plain target object for…
  • Getting error, `Prop `className` did not match` when…
  • Continuous Integration vs. Continuous Delivery vs.…
  • Why is Ember throwing "Uncaught Error: Assertion…
  • PHP-FPM and Nginx: 502 Bad Gateway
  • NextJS deploy to a specific URL path
  • Vue.js build with different environment variables
  • Error R10 (Boot timeout) -> Web process failed to…
  • Vue can I set process.env.NODE_ENV
  • npm install error in vue
  • null terminating a string
  • Implement Firebase simpleLogin email & password…
  • how to test express session
  • Failed to mount component on new laravel 5.5 project
  • What are Maven goals and phases and what is their…
  • Laravel App not running on xampp or live server but…
  • Trying to integrate Ant Design using Sass and…
  • ReactJS states not being rendered correctly
  • Web Application Problems (web.config errors) HTTP…
  • Can't run watch with laravel and vue js
  • Error: request entity too large
  • Check for internet connection with Swift
  • .next folder is missing some files using Docker on…
  • How to POST the data from a modal form of Bootstrap?
  • Express JS: TypeError [ERR_INVALID_ARG_TYPE]: The…
  • Vue Component Library - Can't import from dist
  • setTimeout function not working : javascript

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

Add localization to vue-tables2 table

Next Post:

Binding multiple functions to the same event in backbone

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error