*ESLint Error* in React when trying to deploy Firebase Functions - node.js

Setting up a serverless backend using Firebase Functions. Tutorials I watched setting up the Functions folder all recommended using the ESLint feature to catch probable bugs and enforce style. POST lambda route notified a parsing error when locally deployed but everything still worked as needed. I go to deploy the backend to Firebase and I'm thrown a bunch of errors - thus not letting me continue. I go to the line it says I have an error, remove async await, the error goes away but the code breaks. What am I doing wrong? Is there still a way to deploy my code without having to delete the Functions folder and do it all over again?
index.js file within functions folder:
const functions = require("firebase-functions");
const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();
const stripe = require("stripe")(`${process.env.REACT_APP_STRIPE_SECRET_KEY}`);
// App config
const app = express();
// Middlewares
app.use(cors({origin: true}));
app.use(express.urlencoded({extended: true, useNewUrlParser: true}));
app.use(express.json());
// API routes
app.get("/", (req, res) => res.status(200).send("Hello World"));
// 👇 PARSING ERROR PREVENTING DEPLOY 👇
app.post("/payments/create", async (req, res) => {
const total = req.query.total;
console.log("Payment Request Received for: , total");
const paymentIntent = await stripe.paymentIntents.create({
amount: total, //sub-units of currency
currency: "USD",
});
res.status(201).send({
clientSecret: paymentIntent.client_secret,
})
});
// Listen command
exports.api = functions.https.onRequest(app);
.eslintrc.js file within functions folder:
module.exports = {
root: true,
env: {
es6: true,
node: true,
},
extends: [
"eslint:recommended",
"google",
],
rules: {
quotes: ["error", "double"],
},
};
package.json file within functions folder:
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"lint": "eslint .",
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "12"
},
"main": "index.js",
"dependencies": {
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"firebase-admin": "^9.2.0",
"firebase-functions": "^3.11.0",
"stripe": "^8.137.0"
},
"devDependencies": {
"eslint": "^7.6.0",
"eslint-config-google": "^0.14.0",
"firebase-functions-test": "^0.2.0"
},
"private": true
}
Errors in terminal when trying to deploy:
i deploying functions
Running command: npm --prefix "$RESOURCE_DIR" run lint
> functions# lint /Users/Desktop/coding-repos/ecommerce/client/functions
> eslint .
/Users/Desktop/coding-repos/ecommerce/client/functions/index.js
22:47 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! functions# lint: `eslint .`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the functions# lint script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/.npm/_logs/2021-03-05T22_26_21_954Z-debug.log
Error: functions predeploy error: Command terminated with non-zero exit code1

In these situations, it is a good idea to read the stack trace. The error message points to the issue or what might be the issue that you can debug.
As you can see, the error location is around 22:47 here in your index.js file. Although this is not always precise, you can assume the error will be on that line or possibly above or below it. There are exceptions to this. For example, you might not have closed brackets elsewhere in the code.
/Users/Desktop/coding-repos/ecommerce/client/functions/index.js
22:47 error Parsing error: Unexpected token =>
✖ 1 problem (1 error, 0 warnings)
Also, review the logs as they provide a lot of detailed information to identify what is happening. They can sometimes be hard to understand, but you usually find what you are looking for if you search backwards through the trace.
npm ERR! A complete log of this run can be found in:
npm ERR! /Users/.npm/_logs/2021-03-05T22_26_21_954Z-debug.log
A lot of developers will copy and paste code that they find on the internet. It is good when you need snippets when you are unsure how something works but can be a pain to debug because developers take old code and mix the versions up.
I am more familiar with Python, but my guess is ESlint is having problems with a version of Javascript. Look at this Stackoverflow question as I think it answers your issue. The solution appears to be using a parser.
"parser": "babel-eslint"

Related

Unable to launch express with npm start

How do I correctly create and launch express with npm start? When I do "npm start" I get the following error. Failed at the webserver#1.0.0 start script. I see the following in the error log that hints to the app.js but what is it about the app.js that is incorrect? Thank you.
20 error code ELIFECYCLE
21 error errno 126
22 error webserver#1.0.0 start: `./src/app.js`
22 error Exit status 126
23 error Failed at the webserver#1.0.0 start script.
I have the following package.json file.
{
"name": "webserver",
"preferGlobal": true,
"version": "1.0.0",
"author": "Milton Centeno <centem#gmail.com>",
"description": "a simple express web server",
"license": "MIT",
"main" : "./src/app.js",
"engines": {
"node": ">=0.10"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"express": ">=4.15.3"
}
}
Here is the output of the tree command that shows where my app.js file is relative to package.json.
.
├── node_modules
├── package-lock.json
├── package.json
└── src
└── app.js
And this is what I have for my app.js
// Load the Express package as a module
const express = require("express");
// Access the exported service
const app = express();
// Return a string for requests to the root URL ("/")
app.get("/", (request, response) => {
response.send("Hello from Express!");
});
// Start listening to incoming requests
// If process.env.PORT is not defined, port number 3000 is used
const listener = app.listen(process.env.PORT || 3000, () => {
console.log(`Your app is listening on port ${listener.address().port}`);
});
You need to define a start script: "start": "node src/app.js",.
From the NPM docs:
This runs an arbitrary command specified in the package's "start" property of its "scripts" object. If no "start" property is specified on the "scripts" object, it will run node server.js.

Problem when i run npm run dev in my node backend

I try to build API with node,and i have my frontend separated in folder called client,and this files(package.json,server.js is in my project root folder.
When i want to npm run dev,it gives me this error:
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! clothing-server#1.0.0 dev: `concurrently --kill-others-on-fail "npm server" "npm client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the clothing-server#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
Here is my server.js:
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
if (process.env.NODE_ENV !== 'production') require('dotenv').config();
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
if (process.env.NODE_ENV === 'production') {
app.use(express.static(path.join(__dirname, 'client/build')));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
});
}
app.listen(port, error => {
if (error) throw error;
console.log(`Server running on ${port}`);
});
app.post('/payment', (req, res) => {
const body = {
source: req.body.token.id,
amount: req.body.amount,
currency: 'usd'
};
stripe.charges.create(body, (stripeErr, stripeRes) => {
if (stripeErr) {
res.status(500).send({ error: stripeErr });
} else {
res.status(200).send({ error: stripeRes });
}
});
});
and my package.json:
{
"name": "clothing-server",
"version": "1.0.0",
"engines": {
"node": "10.16.0",
"npm": "6.9.0"
},
"scripts": {
"client": "cd client && npm start",
"server": "nodemon server.js",
"build": "cd client && npm run build",
"dev": "concurrently --kill-others-on-fail \"npm server\" \"npm client\"",
"start": "node server.js",
"heroku-postbuild": "cd client && npm install && npm install --only=dev --no-shrinkwrap && npm run build"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "1.7.4",
"cors": "2.8.5",
"dotenv": "8.2.0",
"express": "^4.17.1",
"stripe": "8.6.0"
},
"devDependencies": {
"concurrently": "^5.0.2"
}
}
I try to delete my lock file and node_modules and npm cache clean ,but they don't help
In your package.json file, It should be
"dev": "concurrently --kill-others-on-fail \"npm run server\" \"npm run client\""
Your npm run dev script calls npm server, which it tries to call nodemon server.js, but apparently the nodemon is not installed in your project. See your list of dependencies, and install nodemon, or remove it from server script.
Apparently it should work ;)

Trying to run concurrently (npm ERR! code ELIFECYCLE npm ERR!)

I am trying to create a Full Stack Node & Vue application that takes data from an API. I am running into an issue where I am trying to run both the client and server concurrently but the code is running into an error. Please bear with me if I am structuring this question wrong as I am still fairly new to coding!
This is the following error log:
[0] Error occurred when executing command: npm run server
[0] Error: spawn cmd.exe ENOENT
[0] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[0] at onErrorNT (internal/child_process.js:469:16)
[0] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] Error occurred when executing command: npm run client
[1] Error: spawn cmd.exe ENOENT
[1] at Process.ChildProcess._handle.onexit (internal/child_process.js:267:19)
[1] at onErrorNT (internal/child_process.js:469:16)
[1] at processTicksAndRejections (internal/process/task_queues.js:84:21)
[1] npm run client exited with code -4058
[0] npm run server exited with code -4058
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! apex-tracker#1.0.0 dev: `concurrently "npm run server" "npm run client"`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the apex-tracker#1.0.0 dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
From what I can tell the program is running fine up until it reaches the "dev" script in my package.json:
{
"name": "apex-tracker",
"version": "1.0.0",
"description": "Apex Legends user statistics tracker",
"main": "server.js",
"scripts": {
"start": "node server",
"server": "nodemon server",
"client": "npm run serve --prefix client",
"dev": "concurrently \"npm run server\" \"npm run client\""
},
"author": "Jared Mackay",
"license": "MIT",
"dependencies": {
"concurrently": "^5.0.1",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"morgan": "^1.9.1",
"node-fetch": "^2.6.0"
},
"devDependencies": {
"nodemon": "^2.0.2"
}
}
prior to the errors, the program ran fine when I ran the npm run server command, however upon installing the client folder and adding the client and dev script that's when I ran into my errors.
Here is my server.js that I am trying to run with the client:
const express = require('express');
const morgan = require('morgan');
const dotenv = require('dotenv');
//Load configuration file
dotenv.config({ path: './config.env' })
const app = express();
//Develper logging
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
//Profile routes
app.use('/api/v1/profile', require('./routes/profile'));
const port=process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server running on ${process.env.NODE_ENV} mode on port ${port}`);
});
I've tried clearing the npm cache, deleting and reinstalling node-modules as well as package-lock.json, but this created more issues rather than fixing them. I had to revert back to an old git commit and now I'm stuck.
I don't think this route .js file is an issue but here it is just in case profile.js:
const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');
router.get('/:platform/:gamertag', async (req, res) => {
try {
const headers = {
'TRN-Api-Key': process.env.TRACKER_API_KEY
}
const { platform, gamertag } = req.params;
const response = await fetch(
`${process.env.TRACKER_API_URL}/profile/${platform}/${gamertag}`,
{
headers
}
);
const data = await response.json();
if(data.errors && data.errors.length > 0) {
return res.status(404).json({
message: 'Profile Not Found'
});
}
res.json(data);
} catch (err) {
console.error(err);
res.status(500).json({
message: 'Server Error'
});
}
});
module.exports = router;
Thank you in advance!
spawn cmd.exe ENOENT
Your program does not know where to find cmd.exe.

Nodemon crashes when trying to use es6 modules but works well with es5

I am trying to run a server using es6 modules but crashes every time I do it and works whenever I use it with es5error message
I have babel installed and have "preset": ["env"] in my .babelrc file but whenever I run it, I have a "syntax error: Invalid or unexpected token". And this is not on one particular project, this is the third project where am experiencing this
import http from 'http';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
// setting up express application
const app = express();
const hostName = '127.0.0.1';
const port = 3000;
const server = http.createServer(app);
// logs request to the console
app.use(logger('dev'))
// Parse incoming data requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
// making a request to the server
app.get('*', (req, res) => res.status(200).send({
message: 'Welcome to the default API route',
}));
server.listen(port, hostName, () => {
console.log(`Server running at http://${hostName}:${port}/`);
});
it supposed to bring out "Welcome to the default API route" to the console but instead, it is an error message. And if the repo is needed, i will gladly supply it
ES6 is not yet supported in the Node runtime by default. You can integrate it like this:
npm i esm && npm i -D nodemon
In your package.json, add this to scripts:
"start": "nodemon -r esm index.js"
(make sure the index.js part of the script matches the name of your server entry point file)
Run npm start
Solution to running nodemon with support for ES6 module import/export syntax.
first, install the esm package:
npm i esm
second, ensure package.json contains the line
"type": "module"
example package.json:
line 6
{
"name": "stack-overflow-example",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"esm": "^3.2.25",
"express": "^4.18.1"
}
}
To run nodemon:
nodemon esm path-to-your/index.js
the file extension is necessary

How to build next.js production?

I try to get a production build in next.js to run it on my server but I can't build next.js production build when I try
npm run build
Does anyone know how to get a prod build in next.js working correctly I did everything in the next.js documentation but always get this error below. If I do a dev build it works just fine but trying prod build results in errors.
I did also next build many times and reinstalled all node_modules packages still having this error.
it always shows me in terminal
Error: Could not find a valid build in the '/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/.next' directory! Try building your app with 'next build' before starting the server.
at Server.readBuildId (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:753:15)
at new Server (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next-server.js:80:25)
at module.exports (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/next.js:6:10)
at Object.<anonymous> (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/next.config.js:6:13)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at loadConfig (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/server/config.js:47:28)
at _callee2$ (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/next/dist/build/index.js:52:42)
at tryCatch (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:62:40)
at Generator.invoke [as _invoke] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:288:22)
at Generator.prototype.(anonymous function) [as next] (/mnt/c/Users/NZXT_YOLO/Desktop/New folder (2)/learnnextjs-demo/node_modules/regenerator-runtime/runtime.js:114:21)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! hello-next#1.0.0 build: `next build`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the hello-next#1.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/kk/.npm/_logs/2018-12-10T19_58_00_588Z-debug.log
server.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
next.config.js
const express = require("express");
const next = require("next");
const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV === "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/projects/:page", (req, res) => {
const page = req.params.page;
let file = "";
switch (page) {
case "example1":
file = "/projects/example1";
break;
case "example2":
file = "/projects/example2";
break;
}
return app.render(req, res, file, { page });
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
});
package.json
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
If anyone has an idea would be so nice! I plan to run this next.js site using node on my AWS server. But to do this I need to get production build of react.js currently I can run just a development build.
Hope someone has an idea.
Thanks in advance!
next build followed by next start should be the right commands to prepare the build for production and run it.
Here's an example for package.json. if you want to export application to run as a static content, something like hosting it in s3 as a static website, you need to run next export
...
"scripts": {
"build": "next build",
"start": "next start",
"export": "next export"
}
...
Make sure you have the above scripts in your package.json then run the following in order
$ npm run build
$ npm run start
If you want to start application with specific port, you can specify -p port as argument for npm run command
npm run start -- -p 3232
If you want to incorporate this into a CI/CD pipeline, you need to have Dockerfile, here's a simple example
FROM node:alpine
#copy source
COPY . /app
# Install deps
RUN cd /app && npm install
# Build
RUN npm run build
ENTRYPOINT [ "npm", "run", "start" ]
Still need more explanation or help, don't hesitate to leave a comment and I will be more than happy to assist.
Seems your server.js config is not correct. Please try moving all you have from your next.config.js to server.js make sure the next.config.js file is empty then create a new npm run script:
"prod_start": "NODE_ENV=production node server.js"
Your package.json should then look like this:
{
"name": "hello-next",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"dev": "node server.js",
"build": "next build",
"prod_start": "NODE_ENV=production node server.js",
"export": "next export"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"#zeit/next-sass": "^1.0.1",
"express": "^4.16.4",
"next": "^7.0.2",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"redux": "^4.0.1",
"video-react": "^0.13.1"
}
}
make sure to run: npm run build && npm run prod_start
Then you should have a production build of react running using next.js
Let me know if you got question.
You must launch next build at your root folder and not inside .next/
There are 3 ways todo it:-
way 1: use next build instead of npm run build
way 2: npm run build npm install -g serve serve -s build
more info: https://create-react-app.dev/docs/deployment/
way 3: after npm run build, Remove / from JS,CSS links from /static/index.html file. eg. replace these 2 lines
<script defer="defer" src="/static/js/main.aa87bc08.js"></script>
<link href="/static/css/main.073c9b0a.css" rel="stylesheet"/>
with these 2 lines
<script defer="defer" src="static/js/main.aa87bc08.js"></script>
<link href="static/css/main.073c9b0a.css" rel="stylesheet" />
now it even work on file:///D:/codes/ProjectName/build/index.html
tell me in the comments if none of the 3 ways work, I'll find, try & tell way 4, 5, etc.

Resources