Categories
JavaScript Answers

How to check if token expired using this JWT library in Node.js?

To check if token expired using this JWT library in Node.js, we get the expiration timestamp and compare it to the current date and time.

For instance, we write

const isTokenExpired = (token) =>
  Date.now() >= JSON.parse(atob(token.split(".")[1])).exp * 1000;

to get the token’s expiration timestamp in milliseconds with

JSON.parse(atob(token.split(".")[1])).exp * 1000

Then we compare it to the current timestamp returned by Date.now.

If the current timestamp is bigger than the token’s timestamp, then the token expired.

Categories
JavaScript Answers

How to change working directory for npm scripts?

To change working directory for npm scripts, we run cd before running our script.

For instance, we write

cd dir && command -args

in our npm script to change the directory to dir with cd before running command with the -args flags.

Categories
JavaScript Answers

How to stub process.env in Node.js?

To stub process.env in Node.js, we set the values in our test.

For instance, we write

it("does something interesting", () => {
  process.env.NODE_ENV = "test";
  // ...
});

afterEach(() => {
  delete process.env.NODE_ENV;
});

to set the process.env.NODE_ENV to 'test' in our test.

And we delete the property in the afterEach callback so it’s removed after each test.

Categories
JavaScript Answers

How to fix Node.js Hostname/IP doesn’t match certificate’s altnames?

To fix Node.js Hostname/IP doesn’t match certificate’s altnames, we proxy to the target URL.

For instance, we write

const proxy = httpProxy.createProxyServer();

proxy.web(req, res, {
  changeOrigin: true,
  target: "https://example.com:3000",
});

to call proxy.web to proxy requests to https://example.com:3000.

If we use HTTPS, we should include the key and certificate by writing

httpProxy
  .createServer({
    ssl: {
      key: fs.readFileSync("valid-ssl-key.pem", "utf8"),
      cert: fs.readFileSync("valid-ssl-cert.pem", "utf8"),
    },
    target: "https://example.com:3000",
    secure: true,
  })
  .listen(443);

to call add call createServer with the key and cert set.

And we proxy requests to https://example.com:3000.

Categories
JavaScript Answers

How to fix global Node modules not found with JavaScript?

To fix global Node modules not found with JavaScript, we set the NODE_PATH environment variable.

We run

echo $NODE_PATH

to print the value of the NODE_PATH environment variable.

If it’s empty, we add

nano ~/.bash_profile
export NODE_PATH=`npm root -g`
source ~/.bash_profile

to add NODE_PATH to the .bash_profile file to make the global packages visible.