0

I'm trying to require an external library in my Node app (Koa server). I'm adding njwt in my main server.js file var njwt = require('njwt');

But I can't access njwt, in my route handler function it gives an error saying njwt is undefined.

From this answer (https://stackoverflow.com/a/5809968), it seems that using strict mode in my main server.js file makes functions and variables defined in my imported file inaccessible.

But what's the workaround?

Louis
  • 128,628
  • 25
  • 249
  • 295
Qasim
  • 1,328
  • 1
  • 11
  • 21

3 Answers3

1

If I am understanding correctly, all you need to do is change it to: var njwt = require('./njwt');

This is assuming you have already done an npm install in the njwt directory.

Jack Ryan
  • 1,255
  • 12
  • 25
1

I think the issue is how to send njwt instance to your router, You can pass njwt instance like this,

require('./routes')(njwt);

Rishabh
  • 120
  • 8
0

I'm not sure if this is the best approach. I just ended up requiring the library in the route handler

const router = require('koa-router')();
router.post('/register', async function(ctx, next) {
    var jwt = require('jsonwebtoken');
    debugger;

And I'm able to access the library this way (the other two methods didn't work for me).

Qasim
  • 1,328
  • 1
  • 11
  • 21