DEV Community

Rafael Lourenço
Rafael Lourenço

Posted on

How to Export Global Variables in Node.js

Imagine you are using Koa.js to create a route, and within that route, you retrieve a key that you intend to use in another router, function, or elsewhere. In such cases, you may want to use the easiest method to export that key for subsequent use.

One of the easiest case are export that key with global variable, to do that you may try weird thinngs likes me

let key = ''
const router = new Router();

router.get('/createkey', async (ctx: ParameterizedContext) => {
  const tokenData = await getToken();
  key= tokenData.access_token ;
  await client.set('createkey', tokenData.access_token, { EX: 2399 });
  ctx.body = 'Key created'
  console.log('Key created')
  console.log(key)
});

export { key, router as default };
Enter fullscreen mode Exit fullscreen mode

Trust me, that doesn't work. The easiest way to achieve this in Node.js is by using the global object.

global.key 
Enter fullscreen mode Exit fullscreen mode
const router = new Router();

router.get('/createkey', async (ctx: ParameterizedContext) => {
  const tokenData = await getToken();
  global.key= tokenData.access_token ;
  await client.set('createkey', tokenData.access_token, { EX: 2399 });
  ctx.body = 'Key created'
  console.log('Key created')
  console.log(global.key)
});


export default router;
Enter fullscreen mode Exit fullscreen mode

With that object, you can access and modify your global variable in every part of your project.

Top comments (0)