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?
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.
I think the issue is how to send njwt instance to your router,
You can pass njwt instance like this,
require('./routes')(njwt);
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).