'Cannot read property 'trim' of undefined in Node.js
const express = require('express')
const barongJwt = require('node-auth-barong')
const app = express()
const port = 3000
const barongJwtPublicKey = Buffer.from(process.env.BARONG_JWT_PUBLIC_KEY.trim(), 'base64').toString('utf-8')
app.get('/protected',
barongJwt({barongJwtPublicKey: barongJwtPublicKey}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
I am working on a Javascript application. Why I am getting "TypeError: Cannot read property 'trim' of undefined"?
const barongJwtPublicKey = Buffer.from(process.env.BARONG_JWT_PUBLIC_KEY.trim(), 'base64').toString('utf-8')
^
TypeError: Cannot read property 'trim' of undefined
Solution 1:[1]
reason for this error is your env file don't have BARONG_JWT_PUBLIC_KEY property or it's value. Things to note
- Make Sure you have .env file and in that file have BARONG_JWT_PUBLIC_KEY in it Sharing an example install dotenv
- On safer side use this as code if you don't follow the step one
const express = require('express')
const barongJwt = require('node-auth-barong')
const app = express()
const port = 3000
const paramString = process.env.BARONG_JWT_PUBLIC_KEY ?? "";
const barongJwtPublicKey = Buffer.from(paramString.trim(), 'base64').toString('utf-8')
app.get('/protected',
barongJwt({barongJwtPublicKey: barongJwtPublicKey}),
function(req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |