Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

node.js - express session not persisting after deploying to heroku and netlify

I deployed my React frontend to netlify, and express backend to Heroku, and I'm using session.

The session works perfectly locally to it doesn't work when I deploy it

When I check the db, session has been made, but when I console.log(req.session) it doesn't logs anything

So, it looks like the session is saved on db, but it doesn't save on the heroku server

Do I need to configure sessions on heroku?


mongoose.connect(
  "mydburl",
  {
    useNewUrlParser: true,
  }
);

const store = new MongoDBStore({
  uri:
    "mydburl",
  collection: "sessions",
});

app.use(
  cors({
    domain: url,
    origin: [url],
    methods: ["GET", "POST", "DELETE"],
    credentials: true,
  })
);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.set("trust proxy", 1);
app.use(
  session({
    key: "userID",
    secret: "subscribe",
    proxy: true,
    resave: false,
    saveUninitialized: false,
    store: store,
    cookie: {
      secure: false,
      httpOnly: false,
      maxAge: null, //1000 * 60 * 60 * 24 * 7, 1 week
      domain: url,
    },
  })
);

app.get("/login", (req, res) => {
  if (req.session.user) {
    console.log(req.session.user);
    res.send({ isLogin: true, user: req.session.user });
  } else {
    console.log("req.session.user doesn't exist");
    res.send("no");
  }
});

app.post("/login", (req, res) => {
  const { username, password } = req.body;

  RegisterModel.find({ username }, (err, result) => {
    if (err) {
      console.log(err);
    }
    if (result.length > 0) {
      bcrypt.compare(password, result[0].password, (error, response) => {
        if (response) {
          req.session.user = result;
          res.send(result);
        } else {
          res.send("????? ?? ????");
        }
      });
    } else {
      res.send("???? ?? ????");
    }
  });
});

question from:https://stackoverflow.com/questions/66062049/express-session-not-persisting-after-deploying-to-heroku-and-netlify

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would really help if you could also add the Front-End part where you are creating the session. But I think combing the front-end and back-end should help you solve this problem.

Deploy both front-end and back-end on Heroku. Change your index.js or server.js whichever is your entry-point of the server to something like this:

...
if (process.env.NODE_ENV === "production") {
  //Set static folder
  app.use(express.static("client/build"));
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server running on port ${port}`));

module.exports = { app };

Here, I have assumed that your front-end part is inside the client folder. You can change it accordingly.

root_folder
   -server.js
   ....rest of server files
   package.json
   -client
        -build
        ....rest of React part
        package.json

Also, add this to your package.json file of server.

"scripts": {
    ....
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
  },

The above command will install the client dependencies first and then create a build for deploying.

Now, if check Heroku URL is https://xyz.herokuapp.com and it should display your front-end and the rest will work the same. Locally you can check this by manually creating a build(npm run build) and changing process.env.NODE_ENV === "production" to process.env.NODE_ENV === "development", also change the build folder path accordingly. Now, check http://localhost:5000 or your local backend server URL.

You can read more about it here: https://create-react-app.dev/docs/deployment/#heroku


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...