I am doing one project in Mern Stack. I am fairly new to backend development and mern stack is my first encounter. Everything was going fine , i tried to use stripe js and it worked fine but I didn't want it in my project. So I decided to replace my entire folder with my previous codes before stripe js. Now the problem is I by mistakenly deleted .env files of both my front end and backend parts and also the package.json files. I tried fixing that by creating .env files again and performed npm install after deleting all the node modules files all together but nothing seems to be working. It gives error "Error: secret should be set" in the node_modules part of backend and this error in the frontend
npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! projfrontend@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the projfrontend@0.1.0 start 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! C:\Users\Raj98\AppData\Roaming\npm-cache\_logs\2020-05-21T19_16_38_946Z-debug.log D:\projfrontend>npm update > core-js-pure@3.6.5 postinstall D:\projfrontend\node_modules\core-js-pure > node -e "try{require('./postinstall')}catch(e){}" //node_modules>express_jwt
var jwt = require('jsonwebtoken'); var UnauthorizedError = require('./errors/UnauthorizedError'); var unless = require('express-unless'); var async = require('async'); var set = require('lodash.set'); var DEFAULT_REVOKED_FUNCTION = function(_, __, cb) { return cb(null, false); }; function isFunction(object) { return Object.prototype.toString.call(object) === '[object Function]'; } function wrapStaticSecretInCallback(secret){ return function(_, __, cb){ return cb(null, secret); }; } module.exports = function(options) { if (!options || !options.secret) throw new Error('secret should be set'); var secretCallback = options.secret; if (!isFunction(secretCallback)){ secretCallback = wrapStaticSecretInCallback(secretCallback); } var isRevokedCallback = options.isRevoked || DEFAULT_REVOKED_FUNCTION; var _requestProperty = options.userProperty || options.requestProperty || 'user'; var _resultProperty = options.resultProperty; var credentialsRequired = typeof options.credentialsRequired === 'undefined' ? true : options.credentialsRequired; var middleware = function(req, res, next) { var token; if (req.method === 'OPTIONS' && req.headers.hasOwnProperty('access-control-request-headers')) { var hasAuthInAccessControl = !!~req.headers['access-control-request-headers'] .split(',').map(function (header) { return header.trim(); }).indexOf('authorization'); if (hasAuthInAccessControl) { return next(); } } if (options.getToken && typeof options.getToken === 'function') { try { token = options.getToken(req); } catch (e) { return next(e); } } else if (req.headers && req.headers.authorization) { var parts = req.headers.authorization.split(' '); if (parts.length == 2) { var scheme = parts[0]; var credentials = parts[1]; if (/^Bearer$/i.test(scheme)) { token = credentials; } else { if (credentialsRequired) { return next(new UnauthorizedError('credentials_bad_scheme', { message: 'Format is Authorization: Bearer [token]' })); } else { return next(); } } } else { return next(new UnauthorizedError('credentials_bad_format', { message: 'Format is Authorization: Bearer [token]' })); } } if (!token) { if (credentialsRequired) { return next(new UnauthorizedError('credentials_required', { message: 'No authorization token was found' })); } else { return next(); } } var dtoken; try { dtoken = jwt.decode(token, { complete: true }) || {}; } catch (err) { return next(new UnauthorizedError('invalid_token', err)); } async.waterfall([ function getSecret(callback){ var arity = secretCallback.length; if (arity == 4) { secretCallback(req, dtoken.header, dtoken.payload, callback); } else { // arity == 3 secretCallback(req, dtoken.payload, callback); } }, function verifyToken(secret, callback) { jwt.verify(token, secret, options, function(err, decoded) { if (err) { callback(new UnauthorizedError('invalid_token', err)); } else { callback(null, decoded); } }); }, function checkRevoked(decoded, callback) { isRevokedCallback(req, dtoken.payload, function (err, revoked) { if (err) { callback(err); } else if (revoked) { callback(new UnauthorizedError('revoked_token', {message: 'The token has been revoked.'})); } else { callback(null, decoded); } }); } ], function (err, result){ if (err) { return next(err); } if (_resultProperty) { set(res, _resultProperty, result); } else { set(req, _requestProperty, result); } next(); }); }; middleware.unless = unless; middleware.UnauthorizedError = UnauthorizedError; return middleware; }; module.exports.UnauthorizedError = UnauthorizedError; //auth.js(controller)
const User = require("../models/user"); const { check, validationResult } = require("express-validator"); var jwt = require("jsonwebtoken"); var expressJwt = require("express-jwt"); exports.signup = (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(422).json({ error: errors.array()[0].msg }); } const user = new User(req.body); user.save((err, user) => { if (err) { return res.status(400).json({ err: "NOT able to save user in DB" }); } res.json({ name: user.name, email: user.email, id: user._id }); }); }; exports.signin = (req, res) => { const errors = validationResult(req); const { email, password } = req.body; if (!errors.isEmpty()) { return res.status(422).json({ error: errors.array()[0].msg }); } User.findOne({ email }, (err, user) => { if (err || !user) { return res.status(400).json({ error: "USER email does not exists" }); } if (!user.autheticate(password)) { return res.status(401).json({ error: "Email and password do not match" }); } //create token const token = jwt.sign({ _id: user._id }, process.env.SECRET); //put token in cookie res.cookie("token", token, { expire: new Date() + 9999 }); //send response to front end const { _id, name, email, role } = user; return res.json({ token, user: { _id, name, email, role } }); }); }; exports.signout = (req, res) => { res.clearCookie("token"); res.json({ message: "User signout successfully" }); }; //protected routes exports.isSignedIn = expressJwt({ secret: process.env.SECRET, userProperty: "auth" }); //custom middlewares exports.isAuthenticated = (req, res, next) => { let checker = req.profile && req.auth && req.profile._id == req.auth._id; if (!checker) { return res.status(403).json({ error: "ACCESS DENIED" }); } next(); }; exports.isAdmin = (req, res, next) => { if (req.profile.role === 0) { return res.status(403).json({ error: "You are not ADMIN, Access denied" }); } next(); }; //auth.js(routes)
var express = require("express"); var router = express.Router(); const { check, validationResult } = require("express-validator"); const { signout, signup, signin, isSignedIn } = require("../controllers/auth"); router.post( "/signup", [ check("name", "name should be at least 3 char").isLength({ min: 3 }), check("email", "email is required").isEmail(), check("password", "password should be at least 3 char").isLength({ min: 3 }) ], signup ); router.post( "/signin", [ check("email", "email is required").isEmail(), check("password", "password field is required").isLength({ min: 1 }) ], signin ); router.get("/signout", signout); module.exports = router; //app.js
require("dotenv").config(); const mongoose = require("mongoose"); const express = require("express"); const app = express(); const bodyParser = require("body-parser"); const cookieParser = require("cookie-parser"); const cors = require("cors"); //My routes const authRoutes = require("./routes/auth"); const userRoutes = require("./routes/user"); const categoryRoutes = require("./routes/category"); const productRoutes = require("./routes/product"); const orderRoutes = require("./routes/order"); //DB Connection mongoose .connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true }) .then(() => { console.log("DB CONNECTED"); }); //Middlewares app.use(bodyParser.json()); app.use(cookieParser()); app.use(cors()); //My Routes app.use("/api", authRoutes); app.use("/api", userRoutes); app.use("/api", categoryRoutes); app.use("/api", productRoutes); app.use("/api", orderRoutes); //PORT const port = process.env.PORT || 8000; //Starting a server app.listen(port, () => { console.log(`app is running at ${port}`); }); I was in my end of this project and unfortunately messed up all the things. Please help me in getting out of this
23 Answers
My problem was that require('dotenv') and the const authRoutes = require('./routes/auth'); were not in the correct order from server.js.
On my original code, I had
const authRoutes = require("./routes/auth"); require("dotenv").config(); So after digging the web, I found the solution from . require("dotenv").config(); should be first and then const authRoutes = require("./routes/auth"); like below.
require("dotenv").config(); const authRoutes = require("./routes/auth"); 1Try to first hardcore the process.env.SECRET(where the values are expected to be matched from the env file), if it works, try: require('dotenv').config({ path: 'env file path' }) in the file. Also, try to put require('dotenv').config({ path: 'env file path' }) at the top of the require statements or somewhere in the top range.
in my case I updated expressJwt where it is mandatory to add secret key along with algorithm.
like this
const authenticate = jwt({ secret: 'secret', algorithms: ['HS256'] });