Sugar Code
Sugar Code

Reputation: 35

JSON object persisting state from previous calls in nodejs express

In my express code I have a config in json, refer to the "template" variable below. I am doing some modifications in it for some purpose in call one and then in my second call when I am trying to get it, it is returning the modified value of field xyz that is A while I expect it to return the original config.

I did try to move that first line "const template = xxx" inside each method so that a new object gets created but it is still having the same issue. How can I fix this?

const express = require("express");
const { db, pgp } = require("../../helpers/dbConnection");
const { auth } = require("../middlewares/Auth");
const router = express.Router();
const template = require('../../config/template.json');

router.get("/callone", async (req, res) => {
    try {

        template.xyz = "A"
        return res.status(200).send();
    }  
    catch (err) {
        return res.status(500).send(err.message);
    }
});

router.get("/calltwo", async (req, res) => {
    try {
        return res.status(200).send(template);
    }  
    catch (err) {
        return res.status(500).send(err.message);
    }
});

Upvotes: 1

Views: 194

Answers (1)

Evert
Evert

Reputation: 99533

This approach is generally a bad idea.

  • It doesn't work if you ever want to scale beyond 1 server.
  • It doesn't work when there's more than 1 user using the system at the same time.

The right way to handle something like this is by adding either a database, or a session system.

Sessions feels like the right approach here, because that concept is specific for letting you store information specific to a user, and store/retrieve that over the course of several requests.

Upvotes: 1

Related Questions