0

I have completed my project using Wordpress as a headless CMS, this work locally; however when deploying to netlify I am getting cannot "TypeError: Cannot read property 'replace' of undefined"

The Error is referencing my node file, which is included below.

I have tried changing my config file, updating my packages, and have reviewed everything locally. Everything works fine locally, and my live server is up and running fine as well, I migrated my server prior to attempting to deploy.

Netlify Build Process and Error Log

12:08:11 PM: Build ready to start
12:08:13 PM: build-image version: 9e0f207a27642d0115b1ca97cd5e8cebbe492f63
12:08:13 PM: build-image tag: v3.3.2
12:08:13 PM: buildbot version: ef8d0929ed0baabafd8bbb7d0b021e1fc24180c0
12:08:13 PM: Fetching cached dependencies
12:08:13 PM: Starting to download cache of 255.0KB
12:08:13 PM: Finished downloading cache in 84.681048ms
12:08:13 PM: Starting to extract cache
12:08:13 PM: Failed to fetch cache, continuing with build
12:08:13 PM: Starting to prepare the repo for build
12:08:14 PM: No cached dependencies found. Cloning fresh repo
12:08:14 PM: git clone https://github.com/rstowe1/wp-portfolio
12:08:14 PM: Preparing Git Reference refs/heads/master
12:08:15 PM: Starting build script
12:08:15 PM: Installing dependencies
12:08:16 PM: Downloading and installing node v10.16.3...
12:08:16 PM: Downloading https://nodejs.org/dist/v10.16.3/node-v10.16.3-linux-x64.tar.xz...
12:08:17 PM: 
##
12:08:17 PM:                                    3.3%
12:08:17 PM: 
##############################################
12:08:17 PM:                  64.3%
12:08:17 PM: 
###################################
12:08:17 PM: ##################################### 100.0%
12:08:17 PM: Computing checksum with sha256sum
12:08:17 PM: Checksums matched!
12:08:19 PM: Now using node v10.16.3 (npm v6.9.0)
12:08:20 PM: Attempting ruby version 2.6.2, read from environment
12:08:21 PM: Using ruby version 2.6.2
12:08:21 PM: Using PHP version 5.6
12:08:21 PM: Started restoring cached node modules
12:08:21 PM: Finished restoring cached node modules
12:08:21 PM: Installing NPM modules using NPM version 6.9.0
12:08:48 PM: > sharp@0.22.1 install /opt/build/repo/node_modules/sharp
12:08:48 PM: > (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
12:08:48 PM: info
12:08:48 PM: sharp
12:08:48 PM:  Downloading https://github.com/lovell/sharp-libvips/releases/download/v8.7.4/libvips-8.7.4-linux-x64.tar.gz
12:08:51 PM: > core-js@2.6.9 postinstall /opt/build/repo/node_modules/core-js
12:08:51 PM: > node scripts/postinstall || echo "ignore"
12:08:51 PM: Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
12:08:51 PM: The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
12:08:51 PM: > https://opencollective.com/core-js 
12:08:51 PM: > https://www.patreon.com/zloirock 
12:08:51 PM: Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
12:08:51 PM: > core-js-pure@3.1.4 postinstall /opt/build/repo/node_modules/core-js-pure
12:08:51 PM: > node scripts/postinstall || echo "ignore"
12:08:51 PM: Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library!
12:08:51 PM: The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: 
12:08:51 PM: > https://opencollective.com/core-js 
12:08:51 PM: > https://www.patreon.com/zloirock 
12:08:51 PM: Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -)
12:08:51 PM: > gatsby-telemetry@1.1.7 postinstall /opt/build/repo/node_modules/gatsby-telemetry
12:08:51 PM: > node src/postinstall.js
12:08:51 PM: > cwebp-bin@5.1.0 postinstall /opt/build/repo/node_modules/cwebp-bin
12:08:51 PM: > node lib/install.js
12:08:52 PM:   ✔ cwebp pre-build test passed successfully
12:08:52 PM: > mozjpeg@6.0.1 postinstall /opt/build/repo/node_modules/mozjpeg
12:08:52 PM: > node lib/install.js
12:08:52 PM:   ✔ mozjpeg pre-build test passed successfully
12:08:52 PM: > pngquant-bin@5.0.2 postinstall /opt/build/repo/node_modules/pngquant-bin
12:08:52 PM: > node lib/install.js
12:08:53 PM:   ✔ pngquant pre-build test passed successfully
12:08:53 PM: > styled-components@4.3.2 postinstall /opt/build/repo/node_modules/styled-components
12:08:53 PM: > node ./scripts/postinstall.js || exit 0
12:08:53 PM: Use styled-components at work? Consider supporting our development efforts at https://opencollective.com/styled-components
12:08:55 PM: npm
12:08:55 PM:  WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/fsevents):
12:08:55 PM: npm
12:08:55 PM: WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.9: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
12:08:55 PM: added 1881 packages from 1026 contributors and audited 31033 packages in 32.537s
12:08:55 PM: found 1 critical severity vulnerability
12:08:55 PM:   run `npm audit fix` to fix them, or `npm audit` for details
12:08:55 PM: NPM modules installed
12:08:56 PM: Started restoring cached go cache
12:08:56 PM: Finished restoring cached go cache
12:08:56 PM: unset GOOS;
12:08:56 PM: unset GOARCH;
12:08:56 PM: export GOROOT='/opt/buildhome/.gimme/versions/go1.12.linux.amd64';
12:08:56 PM: export PATH="/opt/buildhome/.gimme/versions/go1.12.linux.amd64/bin:${PATH}";
12:08:56 PM: go version >&2;
12:08:56 PM: export GIMME_ENV='/opt/buildhome/.gimme/env/go1.12.linux.amd64.env';
12:08:56 PM: go version go1.12 linux/amd64
12:08:56 PM: Installing missing commands
12:08:56 PM: Verify run directory
12:08:56 PM: Executing user command: gatsby build
12:08:59 PM: success open and validate gatsby-configs — 0.062
12:08:59 PM: success load plugins — 0.575
12:08:59 PM: success onPreInit — 0.012
12:09:00 PM: success delete html and css files from previous builds — 0.012
12:09:00 PM: success initialize cache — 0.014
12:09:00 PM: success copy gatsby files — 0.023
12:09:00 PM: success onPreBootstrap — 0.017
12:09:00 PM: info Creating GraphQL type definition for File
12:09:00 PM: error #11321 PLUGIN Cannot read property 'replace' of undefined
12:09:00 PM: "gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle:
12:09:00 PM: Cannot read property 'replace' of undefined
12:09:00 PM: See our docs page for more info on this error: https://gatsby.dev/issue-how-to
12:09:00 PM: 
12:09:00 PM:   TypeError: Cannot read property 'replace' of undefined
12:09:00 PM:   
12:09:00 PM:   - normalize-base-url.js:6 normalizeBaseUrl
12:09:00 PM:     [repo]/[gatsby-source-wordpress]/normalize-base-url.js:6:27
12:09:00 PM:   
12:09:00 PM:   - gatsby-node.js:71 Object.exports.sourceNodes
12:09:00 PM:     [repo]/[gatsby-source-wordpress]/gatsby-node.js:71:29
12:09:00 PM:   
12:09:00 PM:   - api-runner-node.js:236 runAPI
12:09:00 PM:     [repo]/[gatsby]/dist/utils/api-runner-node.js:236:37
12:09:00 PM:   
12:09:00 PM:   - api-runner-node.js:358 resolve
12:09:00 PM:     [repo]/[gatsby]/dist/utils/api-runner-node.js:358:15
12:09:00 PM:   
12:09:00 PM:   - debuggability.js:313 Promise._execute
12:09:00 PM:     [repo]/[bluebird]/js/release/debuggability.js:313:9
12:09:00 PM:   
12:09:00 PM:   - promise.js:488 Promise._resolveFromExecutor
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:488:18
12:09:00 PM:   
12:09:00 PM:   - promise.js:79 new Promise
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:79:10
12:09:00 PM:   
12:09:00 PM:   - api-runner-node.js:357 Promise.mapSeries.plugin
12:09:00 PM:     [repo]/[gatsby]/dist/utils/api-runner-node.js:357:12
12:09:00 PM:   
12:09:00 PM:   - util.js:16 tryCatcher
12:09:00 PM:     [repo]/[bluebird]/js/release/util.js:16:23
12:09:00 PM:   
12:09:00 PM:   - reduce.js:155 Object.gotValue
12:09:00 PM:     [repo]/[bluebird]/js/release/reduce.js:155:18
12:09:00 PM:   
12:09:00 PM:   - reduce.js:144 Object.gotAccum
12:09:00 PM:     [repo]/[bluebird]/js/release/reduce.js:144:25
12:09:00 PM:   
12:09:00 PM:   - util.js:16 Object.tryCatcher
12:09:00 PM:     [repo]/[bluebird]/js/release/util.js:16:23
12:09:00 PM:   
12:09:00 PM:   - promise.js:517 Promise._settlePromiseFromHandler
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:517:31
12:09:00 PM:   
12:09:00 PM:   - promise.js:574 Promise._settlePromise
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:574:18
12:09:00 PM:   
12:09:00 PM:   - promise.js:619 Promise._settlePromise0
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:619:10
12:09:00 PM:   
12:09:00 PM:   - promise.js:699 Promise._settlePromises
12:09:00 PM:     [repo]/[bluebird]/js/release/promise.js:699:18
12:09:00 PM:   
12:09:00 PM: 
12:09:00 PM: Skipping functions preparation step: no functions directory set
12:09:00 PM: Caching artifacts
12:09:00 PM: Started saving node modules
12:09:00 PM: Finished saving node modules
12:09:00 PM: Started saving pip cache
12:09:00 PM: Finished saving pip cache
12:09:00 PM: Started saving emacs cask dependencies
12:09:00 PM: Finished saving emacs cask dependencies
12:09:00 PM: Started saving maven dependencies
12:09:00 PM: Finished saving maven dependencies
12:09:00 PM: Started saving boot dependencies
12:09:00 PM: Finished saving boot dependencies
12:09:00 PM: Started saving go dependencies
12:09:00 PM: Finished saving go dependencies
12:09:02 PM: Error running command: Build script returned non-zero exit code: 1
12:09:02 PM: Failing build: Failed to build site
12:09:02 PM: failed during stage 'building site': Build script returned non-zero exit code: 1
12:09:02 PM: Finished processing build request in 49.113718069s

Gatsby-Node.js

const _ = require(`lodash`)
const Promise = require(`bluebird`)
const path = require(`path`)
const slash = require(`slash`)

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions
  // createRedirect({ fromPath: "/", toPath: "/home", redirectInBrowser: true, isPermanent: true })
  return new Promise((resolve, reject) => {
    // ==== PAGES (WORDPRESS NATIVE) ====
    graphql(
      `
        {
          allWordpressPage {
            edges {
              node {
                id
                slug
                status
                template
                title
                content
                template
              }
            }
          }
        }
      `,
    )
      .then(result => {
        if (result.errors) {
          console.log(result.errors)
          reject(result.errors)
        }

        const pageTemplate = path.resolve("./src/templates/page.js")
        const portfolioUnderContentTemplate = path.resolve("./src/templates/portfolioUnderContent.js")
        _.each(result.data.allWordpressPage.edges, edge => {

          createPage({
            path: `/${edge.node.slug}/`,
            component: slash(edge.node.template === "portfolio_under_content.php" ? portfolioUnderContentTemplate : pageTemplate),
            context: edge.node,
          })
        })
      })
      // ==== END PAGES ====

      // ==== PORTFOLIO ====
      .then(() => {
        graphql(
          `
            {
              allWordpressWpPortfolio{
                edges{
                  node{
                    id
                    title
                    slug
                    excerpt
                    content
                    featured_media{
                      source_url
                    }
                    acf{
                      portfolio_url
                    }
                  }
                }
              }
            }
          `,
        ).then(result => {
          if (result.errors) {
            console.log(result.errors)
            reject(result.errors)
          }
          const portfolioTemplate = path.resolve("./src/templates/portfolio.js")
          _.each(result.data.allWordpressWpPortfolio.edges, edge => {
            createPage({
              path: `/portfolio/${edge.node.slug}/`,
              component: slash(portfolioTemplate),
              context: edge.node,
            })
          })
        })
      })
      // ==== END PORTFOLIO ====
      // ==== BLOG POSTS ====
      .then(() => {
        graphql(`
            {
              allWordpressPost{
                edges{
                  node{
                    excerpt
                    wordpress_id
                    date(formatString: "Do MMM YYYY HH:mm")
                    title
                    content
                    slug
                  }
                }
              }
            }
          `).then(result => {
          if (result.errors) {
            console.log(result.errors)
            reject(result.errors)
          }

          const posts = result.data.allWordpressPost.edges
          const postsPerPage = 2
          const numberOfPages = Math.ceil(posts.length / postsPerPage)
          const blogPostListTemplate = path.resolve("./src/templates/blogPostList.js")

          Array.from({ length: numberOfPages }).forEach((page, index) => {
            createPage({
              component: slash(blogPostListTemplate),
              path: index === 0 ? "/blog" : `/blog/${index + 1}`,
              context: {
                posts: posts.slice(index * postsPerPage, (index * postsPerPage) + postsPerPage),
                numberOfPages,
                currentPage: index + 1,
              },
            })
          })

          const pageTemplate = path.resolve("./src/templates/page.js")
          _.each(posts, (post) => {
            createPage({
              path: `/post/${post.node.slug}`,
              component: slash(pageTemplate),
              context: post.node,
            })
          })

          resolve()
        })
      })
  })
}

Gatsby-Config.js

require('dotenv').config({
  path:'.env'
})

module.exports = {
  siteMetadata: {
    title: `Gatsby Default Starter`,
    description: `Kick off your next, great Gatsby project with this default starter. This barebones starter ships with the main Gatsby configuration files you might need.`,
    author: `@gatsbyjs`,
  },
  plugins: [
    `gatsby-plugin-styled-components`,
    `gatsby-plugin-react-helmet`,
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `images`,
        path: `${__dirname}/src/images`,
      },
    },
    `gatsby-transformer-sharp`,
    `gatsby-plugin-sharp`,
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        name: `gatsby-starter-default`,
        short_name: `starter`,
        start_url: `/`,
        background_color: `#663399`,
        theme_color: `#663399`,
        display: `minimal-ui`,
        icon: `src/images/gatsby-icon.png`, // This path is relative to the root of the site.
      },
    },
    {
      resolve: "gatsby-source-wordpress",
      options: {

        baseUrl: process.env.API_URL,
        protocol: process.env.API_PROTOCOL,
        hostingWPCOM: false,
        useACF: true,
        acfOptionPageIds: [],
        auth: {
          htaccess_user: "your-htaccess-username",
          htaccess_pass: "your-htaccess-password",
          htaccess_sendImmediately: false,
          wpcom_app_clientSecret: process.env.WORDPRESS_CLIENT_SECRET,
          wpcom_app_clientId: "54793",
          wpcom_user: "gatsbyjswpexample@gmail.com",
          wpcom_pass: process.env.WORDPRESS_PASSWORD,
          jwt_user: process.env.JWT_USER,
          jwt_pass: process.env.JWT_PASSWORD,
          jwt_base_path: "/jwt-auth/v1/token",
        },
        cookies: {},
        verboseOutput: false,
        perPage: 100,
        searchAndReplaceContentUrls: {
          sourceUrl: "https://source-url.com",
          replacementUrl: "https://replacement-url.com",
        },
        concurrentRequests: 10,
        includedRoutes: [
          "**/*/*/categories",
          "**/*/*/posts",
          "**/*/*/pages",
          "**/*/*/media",
          "**/*/*/tags",
          "**/*/*/taxonomies",
          "**/*/*/users",
          "**/*/*/menus",
          "**/*/*/portfolio",
        ],
        excludedRoutes: [],
        normalizer: function({ entities }) {
          return entities
        },
      },
    },
    'gatsby-plugin-netlify'
  ],
}

Package.json

{
  "name": "gatsby-starter-default",
  "private": true,
  "description": "A simple starter to get up and developing quickly with Gatsby",
  "version": "0.1.0",
  "author": "Kyle Mathews <mathews.kyle@gmail.com>",
  "dependencies": {
    "@material-ui/core": "^4.3.0",
    "babel-plugin-styled-components": "^1.10.6",
    "gatsby": "^2.13.45",
    "gatsby-image": "^2.2.7",
    "gatsby-plugin-manifest": "^2.2.4",
    "gatsby-plugin-netlify": "^2.1.3",
    "gatsby-plugin-offline": "^2.2.4",
    "gatsby-plugin-react-helmet": "^3.1.2",
    "gatsby-plugin-sharp": "^2.2.9",
    "gatsby-plugin-styled-components": "^3.1.2",
    "gatsby-source-filesystem": "^2.1.7",
    "gatsby-source-wordpress": "^3.1.12",
    "gatsby-transformer-sharp": "^2.2.5",
    "prop-types": "^15.7.2",
    "react": "^16.8.6",
    "react-dom": "^16.9.0",
    "react-grid-system": "^4.4.11",
    "react-helmet": "^5.2.1",
    "styled-components": "^4.3.2"
  },
  "devDependencies": {
    "prettier": "^1.18.2"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "scripts": {
    "build": "gatsby build",
    "develop": "gatsby develop",
    "format": "prettier --write src/**/*.{js,jsx}",
    "start": "npm run develop",
    "serve": "gatsby serve",
    "test": "echo \"Write tests! -> https://gatsby.dev/unit-testing\""
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/gatsbyjs/gatsby-starter-default"
  },
  "bugs": {
    "url": "https://github.com/gatsbyjs/gatsby/issues"
  }
}

I need to know where I messed up so that I can get this fixed and deployed!!!!!!!!

any insight into my error will be greatly appreciated!

rstowe1
  • 71
  • 1
  • 4
  • 14
  • 1
    can you post full error stack from Netlify, none of your JS files posted above have `.replace` method on anything – Rikin Aug 25 '19 at 03:20
  • @Rikin I have updated the original post to include the Netlify build process and errors – rstowe1 Aug 26 '19 at 16:10
  • Based on that it says issue in executing `gatsby-source-wordpress`. I would suggest you to run build command locally that you are using on netlify and see of you are able to reproduce the same error. Hard to tell, but probably something in your config file that's not right. – Rikin Aug 26 '19 at 16:16
  • I have attempted to run it locally, and I get a successful build everytime – rstowe1 Aug 26 '19 at 16:17
  • are you using the same build command that you have on netlify? – Rikin Aug 26 '19 at 16:17
  • yes, I am using all of the same commands – rstowe1 Aug 26 '19 at 16:19
  • do you have `process.env.API_URL` set in your netlify? – Rikin Aug 26 '19 at 17:19

1 Answers1

3

Based on the error message that you provided from Netlify

12:09:00 PM: info Creating GraphQL type definition for File
12:09:00 PM: error #11321 PLUGIN Cannot read property 'replace' of undefined
12:09:00 PM: "gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle:
12:09:00 PM: Cannot read property 'replace' of undefined
12:09:00 PM: See our docs page for more info on this error: https://gatsby.dev/issue-how-to
12:09:00 PM: 
12:09:00 PM:   TypeError: Cannot read property 'replace' of undefined
12:09:00 PM:   
12:09:00 PM:   - normalize-base-url.js:6 normalizeBaseUrl
12:09:00 PM:     [repo]/[gatsby-source-wordpress]/normalize-base-url.js:6:27
12:09:00 PM:   
12:09:00 PM:   - gatsby-node.js:71 Object.exports.sourceNodes
12:09:00 PM:     [repo]/[gatsby-source-wordpress]/gatsby-node.js:71:29

It is complaining that cannot read property 'replace' of undefined. replace is a method of String in JS and instead it found undefined and tried to call undefined.replace which dont exist which indicates you dont seem to have API_URL in Netlify's environment variables.

You can go to your Site's deployment settings and scroll down to Environment variables which would be somewhat like this URL and add your API_URL over there: https://app.netlify.com/sites/*****/settings/deploys#environment

Alternatively you can hardcode it in your config direct.

{
      resolve: "gatsby-source-wordpress",
      options: {
        baseUrl: process.env.API_URL,
        protocol: process.env.API_PROTOCOL,
        ...
        searchAndReplaceContentUrls: {
          sourceUrl: "https://source-url.com",
          replacementUrl: "https://replacement-url.com",
        },
        ...
        normalizer: function({ entities }) {
          return entities
        },
      },
    },
Rikin
  • 5,351
  • 2
  • 15
  • 22
  • Not sure what you mean there, you are getting some other errors you mean? – Rikin Aug 26 '19 at 17:32
  • This is my new error message: ``` The request failed with error code "ECONNREFUSED" error #11321 PLUGIN Cannot read property 'data' of undefined "gatsby-source-wordpress" threw an error while running the sourceNodes lifecycle: Cannot read property 'data' of undefined See our docs page for more info on this error: https://gatsby.dev/issue-how-to TypeError: Cannot read property 'data' of undefined - fetch.js:141 fetch [repo]/[gatsby-source-wordpress]/fetch.js:141:21 -next_tick.js:68 process._tickCallback internal/process/next_tick.js:68:7 ``` – rstowe1 Aug 26 '19 at 17:34
  • can you post a new question with complete error log and I'll try to look into that, include config.js in there too along with all the environment variables that you have set (you canmodify its value for example sake) – Rikin Aug 26 '19 at 17:39
  • the new post can be found as follows: https://stackoverflow.com/questions/57663059/netlify-deploy-with-results-of-typeerror-cannot-read-property-data-of-undefin – rstowe1 Aug 26 '19 at 18:28