Access and modify an in-memory variable from Next.js API routes

Viewed 21

I have a couple API routes and I want to get and modify an object that I defined in another file.

Is this posible?

For example,

In inMemoryDB.js I defined the variable:

export const test = {
    ['key1']: {
      id: '...',
      name: 'jane'
   }
}

Then in pages/api:

  • In endpoint 1, I read test, and modify it test['key1'].name = 'john'.
  • In endpoint 2, when I read test['key1'].name it still says 'jane'.

Code:

inMemoryDB.ts

export const testDB = {
  ['key1']: {
    id: 'key1',
    name: 'jane'
  }
};

pages/api/in-memory-test/endpoint1.ts

import type { NextApiRequest, NextApiResponse } from 'next';

import { testDB } from '../../../src/constants/inMemoryDB';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case 'GET':
      return getEndpoint1(req, res);

    default:
      return res.status(400).json({
        message: 'Bad request'
      });
  }
}

const getEndpoint1 = async (req: NextApiRequest, res: NextApiResponse) => {
  console.log('[testDB - 1]', testDB);

  testDB['key1'].name = 'john';

  return res.status(200).json({ testDB });
};

pages/api/in-memory-test/endpoint2.ts

import type { NextApiRequest, NextApiResponse } from 'next';
import { testDB } from '../../../src/constants/inMemoryDB';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  switch (req.method) {
    case 'POST':
      return postEndpoint2(req, res);

    default:
      return res.status(400).json({
        message: 'Bad request'
      });
  }
}

const postEndpoint2 = async (req: NextApiRequest, res: NextApiResponse) => {
  return res.status(200).json({ testDB });
};

When I do GET request to endpoint1:

{
    "testDB": {
        "key1": {
            "id": "key1",
            "name": "john"
        }
    }
}

And then testDB['key1'].name change to 'john' seems to persist in this endpoint.

But when later I do POST request to endpoint2:

{
    "testDB": {
        "key1": {
            "id": "key1",
            "name": "jane"
        }
    }
}
0 Answers
Related