Heroku Deployment Error: displaying backend, not frontend - heroku

I am trying to deploy my local MERN application to Heroku. Application works offline. After deployment, when click "Open app", all I see is the data from the backend. Not the front end. Deployment here: https://whispering-falls-45660.herokuapp.com/.
Set up new Heroku project, and after successful "git push Heroku master", application only shows backend data. Heroku CLI version: heroku/7.24.1, Node version: v10.13.0.
Github repo: https://github.com/neilhsieh/whereToEat
Package.json file has the proper scripts in place as per Brad Traversy:
"scripts": {
"start": "node server.js",
"server": "nodemon server.js",
"client": "npm start --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
server.js code has appropriate code to point to client build file:
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'))
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html')) // relative path
})
}
Expecting front end deployed on Heroku, ended up only having backend.
UPDATE: Moved process.env.NODE_ENV test to before all API calls, this fixed my issue.

First if you have a route like this in your server/app.js file
app.get("/", (req, res) => res.send("Api Running"));
Definitely get rid of that
Second add these lines in your server/app.js file
const path = require("path");
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}

Related

Custom Node server causes Nextjs to fail to load 'No `pages` directory found'

I'm trying to bootstrap a new Nextjs app, and for integrating with Auth0 I need my localhost to be running HTTPS. I followed the guide here (https://medium.com/responsetap-engineering/nextjs-https-for-a-local-dev-server-98bb441eabd7), and generated a local certificate which is in more trusted certificate store.
To use HTTPS for localhost, you apparently need to create a custom server (this seems an odd oversight on the Nextjs side), so here's my custom server:
const { createServer } = require('https');
const { parse } = require('url');
const next = require('next');
const fs = require('fs');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev, dir: __dirname });
const handle = app.getRequestHandler();
const httpsOptions = {
key: fs.readFileSync('./certificates/ReactDevCertificate.key'),
cert: fs.readFileSync('./certificates/ReactDevCertificate.cer'),
};
app.prepare().then(() => {
createServer(httpsOptions, (req, res) => {
const parsedUrl = parse(req.url, true);
handle(req, res, parsedUrl);
}).listen(3000, (err) => {
if (err) throw err;
console.log('> Server started on https://localhost:3000');
});
});
Now, previous without the custom server, the app loads fine. But, with the custom server, it fails to load:
➜ yarn run dev
yarn run v1.22.15
$ next dev ./server.js
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
Error: > No `pages` directory found. Did you mean to run `next` in the parent (`../`) directory?
at Object.findPagesDir (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\lib\find-pages-dir.js:31:15)
at new DevServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\dev\next-dev-server.js:110:44)
at NextServer.createServer (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:102:20)
at C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:117:42
at async NextServer.prepare (C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\server\next.js:92:24)
at async C:\Clients\ING\Framework\samples\fictionist-ui\node_modules\next\dist\cli\next-dev.js:126:9
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
It feels like somewhere the app has navigated to a child folder, as there is code in the function find-pages-dir.js (https://github.com/vercel/next.js/blob/canary/packages/next/lib/find-pages-dir.ts#L22) that looks specifically to the parent directory for the pages folder.
For reference, here is my package.json:
{
"name": "fictionist-ui",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev ./server.js",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "12.0.1",
"react": "17.0.2",
"react-dom": "17.0.2",
"semantic-ui-css": "^2.4.1",
"semantic-ui-react": "^2.0.4"
},
"devDependencies": {
"#types/node": "16.11.6",
"#types/react": "17.0.33",
"eslint": "7.32.0",
"eslint-config-next": "12.0.1",
"typescript": "4.4.4"
}
}
OS: Windows 11
NPM: 16.9.0
Yarn: 1.22.15
My mistake was that I didn't get the command right:
"scripts": {
"dev": "node server.js" // was "next dev ./server.js"
}

Vercel/NextJS: How to access serverless functions from frontend during local development?

My React/NextJS front end has a Button component that fetches data via a serverless function when the button is clicked. I want to test this functionality during local development with the Vercel dev/CLI tools. I am getting a 404 result when attempting to access my lambda functions. Here are the approximate steps that I've gone through so far:
Create package.json with a dev script:
...
"scripts": {
"dev": "yarn codegen && next --hostname=0.0.0.0 --port=3001",
}
...
Link to deployed vercel project
Create vercel.json to specify builds and routes:
...
"builds": [
{ "src": "*.html", "use": "#now/static" },
{ "src": "pages/api/*.py", "use": "#now/python" },
],
"routes": [
{ "src": "/api/validate", "dest": "/pages/api/validate.py" }
]
...
Create my test Lambda function (in python):
from http.server import BaseHTTPRequestHandler
from datetime import datetime
class handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write(str(datetime.now().strftime('%Y-%m-%d %H:%M:%S')).encode())
return
Create my Button component:
...
<Button
variant="contained"
color="secondary"
onClick={() => {
fetch('api/validate')
.then(response => { console.log(response)
response.json() })
.then(data => console.log(data))
}}
>
Generate sample dataset
</Button>
...
Run vercel dev
Access website at localhost:3001 (next dev server address)
Click button
Result:
I'm receiving a 404 response
Note: I can access the lambda function from localhost:3000/pages/api/validate.py (vercel dev server address). This appears to manually kickstart the lambda function build and serve process. I thought that it should have been built and served already from the vercel.json specification and be available at localhost:3001/api/validate. This seems to agree with the Vercel documentation.
Note 2: Next dev/CLI tools build and serve javascript/typescript files just fine. I'm using python and Go functions as well, which are supported by Vercel dev/CLI but not Next
My solution was to use vercel dev instead of next dev or yarn dev, and to use an environment variable in a .env file that points to the function url. This env variable should be prepended with NEXT_PUBLIC_ so that it is registered by next.js and passed to process.env during the build process.
# .env
NEXT_PUBLIC_FUNCTIONS_BASE_URL="http://localhost:3000" # 3000 is vercel port
# component.js
...
fetch(process.env.NEXT_PUBLIC_FUNCTIONS_BASE_URL + '/api/function-name')
...
You need to pass the port from vercel dev to the upstream CLI, in this case next dev.
{
"scripts": {
"dev": "yarn codegen && next dev --port=$PORT",
}
}
Now when you run vercel dev, the ephemeral port will be proxied from the dev server.
You can also remove vercel.json if you rename /pages/api to /api.

How to pass `--` when used with pre npm scripts

How to pass others flags into npm command that has pre config
"prebuild": "npm run build:vendor",
"build": "cross-env NODE_ENV=production webpack --env.production -p",
When I run npm run build -- --env.produciton the flag --env.produciton does not work
I want to pass into webpack command.. ending like this
cross-env NODE_ENV=production webpack --env.production -p --env.production
two options to pass params, one over node cross-env:
"build": "cross-env NODE_ENV=production YOUR_ENV=yourName webpack -p"
if (process.env.YOUR_ENV === 'yourName') { }
the other with webpack:
"build": "webpack --env.NODE_ENV=local --env.YOUR_ENV yourName --progress"
const path = require('path');
module.exports = env => {
// Use env.YOUR_ENV here:
console.log('YOUR_ENV: ', env.YOUR_ENV); // 'yourName'
return {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
};
The param is always true if you won't set value.
https://webpack.js.org/guides/environment-variables/
Setting up your env variable without assignment, --env.production sets --env.production to true by default..

Pass environment variable through PM2 to NextJS

I have 2 package.json scripts that look like this:
"start": "next start -p $PORT",
"pm2_staging": "pm2 restart ecosystem.config.js --env staging",
And an ecosystem.config.js that looks like this:
module.exports = {
apps: [
{
name: 'test.co.uk',
script: 'npm',
args: 'start',
env_staging: {
API: 'staging',
NODE_ENV: 'production',
PORT: 3001,
},
},
],
};
I then run the following:
TEST_VAR='test' npm run pm2_staging
I would expect the following to happen:
The PM2 restart command fires
ecosystem.config.js fires the npm start command and sets some environment variables
The app starts and all env vars are available, including TEST_VAR (set in the original command)
What actually happens is all the env vars from the ecosystem are correctly set, but TEST_VAR is not available in the app. Why is this and how do I go about setting secret keys from CI tools if I can't do this?
I ran into the same problem tonight. After looking every where I found the config needed. The env variable needs to go in your ecosystem.config.js like below. In my case I put it at the root of my server
module.exports = {
apps : [{
name: 'nextjs',
script: 'yarn',
args:"start",
cwd:"/var/www/myapp/",
instances: 2,
autorestart: true,
watch: false,
max_memory_restart: '1G',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production',
API_URL: 'YOUR ENV URL',
PORT:8000
}
}]
};
package.json like so
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start -p 8000"
},
...
and executed something like this
#!/bin/bash
cd /var/www/myapp/
git pull && yarn install && yarn build
cd ~/
pm2 start ecosystem.config.js --env production
Then the API_URL would be available in const API_URL = process.env.API_URL in your app.
These urls helped
https://willandskill.se/en/setup-a-next-js-project-with-pm2-nginx-and-yarn-on-ubuntu-18-04/
https://pm2.keymetrics.io/docs/usage/application-declaration/
Another idea would be passing all the env parameters of PM2 to the server via the following.
ecosystem.config.js being:
module.exports = {
apps: [{
name: "my-service-1",
script: "dist/server.js",
env_production: process.env, // pass all the env params of the container to node
}],
};
#webface
The environment variables in your example will not be available in Nextjs. To be available to both the client and server, variables must be prefixed with NEXT_PUBLIC (ie. NEXT_PUBLIC_API_VERSION).
These environment variables must be passed into the build process to be available at runtime.

Dev dependencies needed for Heroku webpack build

I was under the impression that I wouldn't need the devDependencies to be included when I deploy to Heroku a react based app, using Webpack. For example, here's my package.
"scripts": {
"test": "",
"start": "./node_modules/.bin/babel-node server",
"build": "rimraf dist && export NODE_ENV=production && webpack --config ./webpack.production.config.js --progress --profile --colors",
"postinstall": "node deploy",
"eslint": "eslint .",
"jscs": "jscs ."
},
and deploy.js:
if (process.env.NODE_ENV === 'production') {
var child_process = require('child_process');
child_process.exec("webpack -p --config webpack.production.config.js", function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});
}
and the Procfile
web ./node_modules/.bin/babel-node server.js
However, when I push to Heroku, I'm constantly getting a webpack command not recognized, so I included all of the devDependencies as normal dependencies to have it working. Am I missing something here?
Heroku set NPM_CONFIG_PRODUCTION to true by default to install dependencies only. If you would like to install devDependencies, you can disable production mode:
$ heroku config:set NPM_CONFIG_PRODUCTION=false
However, since you usually don’t want all devDependencies in your production builds, it’s preferable to move only the dependencies you actually need for production builds into dependencies (bower, grunt, gulp, etc).

Resources