Skip to content
Fix Code Error

Heroku deploy fails with react and next js

April 23, 2021 by Code Error
Posted By: Anonymous

My react/next js app works perfectly fine (zero errors/warnings) in my localhost and somehow fails to deploy on Heroku.
When I deploy, I consistently get the same error stating that my posts array (in pages/landing.js) is undefined.

I tried debugging and creating a support ticket as suggested in the logs, but Heroku support was unable to help.

I added log statements as log 1,2, what are the posts,3 and in the deploy logs, I only see “log 3 landing js undefined” so it somehow skips the API call and the client-side log from the pages.index.js

This is what my code looks like:

// pages/index.js
import React from "react";
import Landing from "./landing";
import Layout from "../src/components/layout";
import fetch from "isomorphic-unfetch";
import Error from "next/error";

const Index = ({ posts }) => (
  <Layout>
    <div>
      {console.log("what are the posts???", posts)}
      <Landing posts={posts} />
    </div>
  </Layout>
);

export default Index;

Index.getInitialProps = async () => {
  console.log("log 1");
  const res = await fetch("http://localhost:3000/api/posts");

  const json = await res.json();
  console.log("log 2 what is json", json);
  return { posts: json.posts };
};

//pages/landing.js
import React from "react";
import Navigation from "../src/components/navigation";
import Layout from "../src/components/layout";
import Link from "next/link";
import ReactMarkdown from "react-markdown";

const Landing = ({ posts }) => {
  return (
    <Layout>
      <Navigation />
// ...
      {console.log("log 3 landing js ", posts)}
            {posts.map(post => (
              <h1>post.title</h1>
            ))}
      <Navigation />
    <Layout>
export default Landing;

//package.json
{
  "version": "1.0.0",
  "private": true,
  "engines": {
    "node": "12.2.0",
    "npm": "6.4.1",
    "yarn": "1.13.0"
  },
  "dependencies": {
    "bootstrap": "^4.4.1",
    "isomorphic-unfetch": "^3.0.0",
    "next": "^9.1.4",
    "raw-loader": "^4.0.0",
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-markdown": "^4.2.2",
    "react-scripts": "3.2.0"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start -p $PORT"
  },
  "eslintConfig": {
    "extends": "react-app"
  }
}
// next.config.js

module.exports = {
  webpack: config => {
    config.module.rules.push({
      test: /.md$/,
      use: "raw-loader"
    });

    return config;
  }
};

And finally,the Heroku deploy log:

-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NODE_ENV=production
       NODE_MODULES_CACHE=true
       NODE_VERBOSE=false

-----> Installing binaries
       engines.node (package.json):  12.2.0
       engines.npm (package.json):   6.4.1
       engines.yarn (package.json):  1.13.0

       Resolving node version 12.2.0...
       Downloading and installing node 12.2.0...
       Bootstrapping npm 6.4.1 (replacing 6.9.0)...
       npm 6.4.1 installed
       Resolving yarn version 1.13.0...
       Downloading and installing yarn (1.13.0)...
       Installed yarn 1.13.0

-----> Installing dependencies
       Installing node modules (yarn.lock)
       yarn install v1.13.0
       [1/4] Resolving packages...
       [2/4] Fetching packages...
       info [email protected]: The platform "linux" is incompatible with this module.
       info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
       info [email protected]: The platform "linux" is incompatible with this module.
       info "[email protected]" is an optional dependency and failed compatibility check. Excluding it from installation.
       [3/4] Linking dependencies...
       warning " > [email protected]" has unmet peer dependency "[email protected] - 3".
       warning " > [email protected]" has unmet peer dependency "[email protected]^1.16.0".
       warning " > [email protected]" has unmet peer dependency "[email protected]^4.0.0 || ^5.0.0".
       warning "react-scripts > @typescript-eslint/eslint-plugin > [email protected]" has unmet peer dependency "[email protected]>=2.8.0 || >= 3.2.0-dev || >= 3.3.0-dev || >= 3.4.0-dev || >= 3.5.0-dev || >= 3.6.0-dev || >= 3.6.0-beta || >= 3.7.0-dev || >= 3.7.0-beta".
       [4/4] Building fresh packages...
       Done in 52.24s.

-----> Build
       Running build (yarn)
       yarn run v1.13.0
       $ next build
       Creating an optimized production build...
       Attention: Next.js now collects completely anonymous telemetry regarding usage.
       This information is used to shape Next.js' roadmap and prioritize features.
       You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
       https://nextjs.org/telemetry


       Compiled successfully.

       Automatically optimizing pages...
       log 3 landing js  undefined
Error occurred prerendering page "/landing": TypeError: Cannot read property 'map' of undefined
    at Landing (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/.next/server/static/ATrNApXPLQXluLPvZMJ2m/pages/landing.js:4246:32)
    at d (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:36:498)
    at Za (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:39:16)
    at a.b.render (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:476)
    at a.b.read (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:44:18)
    at renderToString (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/react-dom/cjs/react-dom-server.node.production.min.js:54:364)
    at render (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/next/dist/next-server/server/render.js:81:16)
    at Object.renderPage (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/next/dist/next-server/server/render.js:323:20)
    at /tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/.next/server/static/ATrNApXPLQXluLPvZMJ2m/pages/_document.js:2046:21
    at Generator.next (<anonymous>)
> Build error occurred
Error: Export encountered errors
    at _default (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/next/dist/export/index.js:15:788)
    at processTicksAndRejections (internal/process/task_queues.js:89:5)
    at async build (/tmp/build_e6fcf8d3b8da4774fe2ba078e3d46384/node_modules/next/dist/build/index.js:20:145)
error Command failed with exit code 1.
       info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:
       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

       If you're stuck, please submit a ticket so we can help:
       https://help.heroku.com/

       Love,
       Heroku

 !     Push rejected, failed to compile Node.js app.
 !     Push failed

Solution

Since your landing page does not have a getInitialProps, next.js is trying to prerender it, so the post is undefined. One of the things you could do is to move your landing into components.

If you need posts on every page, you may use getInitialProps in a custom app, like it’s described in the docs


the below is actually an answer to another question

I guess, using localhost:3000 on your Heroku instance is not quite correct. Instead, you could get the api page’s url from the request headers, so your getInititalProps could look similar to this:

Index.getInitialProps = async ctx => {
  if (ctx.req) {
    const host = ctx.req.headers['x-forwarded-host'];
    const proto = ctx.req.headers['x-forwarded-proto'];
    const port =  ctx.req.headers['x-forwarded-port'];

    const res = await fetch(`${proto}//${host}:${port}/api/posts`);

    const json = await res.json();
    return { posts: json.posts };
  } else {
    // otherwise we are in the browser
    const res = await fetch(`/api/posts`);

    const json = await res.json();
    return { posts: json.posts };
  }
}

I’ve looked it up here: https://spectrum.chat/next-js/general/calling-pages-api-directly-in-ssr-getinitialprops~8416c24b-19dc-46eb-aab7-8943a0c4a92e

Answered By: Anonymous

Related Articles

  • useEffect Error: Minified React error #321 (GTM…
  • Heroku "Missing required flag -a --app" error after…
  • Error 'Map', but got one of type 'Null' flutter web with…
  • Why am I getting a "401 Unauthorized" error in Maven?
  • Discord.js: how can I make paticular permissons for each…
  • Apache server keeps crashing, "caught SIGTERM, shutting…
  • Can scanf() function take single character value?
  • How to link a folder with an existing Heroku app
  • How do i add two models to one view?
  • How does PHP 'foreach' actually work?

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:

Ember-Simple-Auth currentUser example help required

Next Post:

Call method in collection, when View’s method called

Leave a Reply Cancel reply

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

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error