I'm making a nodeJS web app and I'm using JWT for authentication. All my work is in ES6 modules and I wanted to import JWT in the same way, but apparently it isn't yet supported by the package. I can't use the older require() format as it throws an error since I've set it to modules in my package.json. Is there a way around this or do I have to find another library altogether?
Edit: I have fixed the issue with destructuring but it's still not working. Apparently it can't find the module at all. I made sure the package is in fact installed and updated, still not working
Error [ERR_MODULE_NOT_FOUND]: Cannot find package 'jsonwebtoken' imported from /path/to/file.js
import jwt from ' jsonwebtoken'
const { sign } = jwt
class sampleClass {
static func(user) {
return sign(
{
_id: user._id,
name: user.name,
},
'sample key',
{
expiresIn: '7d',
},
)
}
}
Your gonna need to import it and then assign it like this
import jwt from 'jsonwebtoken';
const { sign, verify } = jwt;
const token = sign({"d":"dd"}, "secret", {expiresIn: 300})
console.log(token);
const verifycode = verify(token, "secret");
console.log(verifycode);
Could you try something:
Create a folder
Do npm init
Create a file app.js
install json web token npm i jsonwebtoken
Go to package.json and add "type": "module"
write in your app.js this here: import jwt from "jsonwebtoken"
Execute it: node --experimental-modules app.js
Tell me then if you get an error
If you are using jwt v8, just import the jsonwebtoken this way:
import * as jwt from 'jsonwebtoken'
or
import { sign, decode, verify } from 'jsonwebtoken'
You have an extra space in import jwt from ' jsonwebtoken'
Should just be import jwt from 'jsonwebtoken'
I just tested it and it works fine on my computer
I am using typescript to write my node server and jwt implementation.
This is the suggestion on my terminal:
Try npm i --save-dev #types/jsonwebtoken if it exists or add a new declaration (.d.ts) file containing `declare module 'jsonwebtoken';
I just typed: npm i --save-dev #types/jsonwebtoken
Then in my file I added imports: import jwt from "jsonwebtoken"
Hope that helps.
Related
I'm attempting to create an apollo client plugin for a Nuxt 3 application. It's currently throwing an error regarding a package called ts-invariant:
file:///Users/[my name]/Repositories/[project]/node_modules/#apollo/client/utilities/globals/fix-graphql.js:1
import { remove } from "ts-invariant/process/index.js";
^^^^^^
SyntaxError: Named export 'remove' not found. The requested module 'ts-invariant/process/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'ts-invariant/process/index.js';
const { remove } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:124:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:181:5)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:281:24)
at async __instantiateModule__ (file:///Users/[my name]/Repositories/[project]/.nuxt/dist/server/server.mjs:4550:3)
[vite dev] Error loading external "/Users/[my name]/Repositories/[project]/node_modules/#apollo/client/core/index.js".
at file://./.nuxt/dist/server/server.mjs:3170:289
at async __instantiateModule__ (file://./.nuxt/dist/server/server.mjs:4550:3)
I feel like I know enough about this error to know it has something to do with how Nuxt 3 deals with ESM, but I can't be for certain.
Here's the nuxt plugin:
plugins/apollo-client.js
import { defineNuxtPlugin } from "#app"
import { ApolloClient, InMemoryCache } from "#apollo/client/core"
import { DefaultApolloClient } from "#vue/apollo-composable"
export default defineNuxtPlugin((nuxtApp) => {
const config = useRuntimeConfig()
const apolloClient = new ApolloClient({
uri: config.PUBLIC_API_ENDPOINT,
cache: new InMemoryCache(),
})
nuxtApp.vueApp.provide(DefaultApolloClient, apolloClient)
})
In a normal scenario, I might use the nuxt-apollo community module, but it is currently afk regarding a nuxt 3 port, so a plugin it is.
Here's some documentation I relied on for my plugin:
https://v4.apollo.vuejs.org/guide-composable/setup.html#vue-3
https://v3.nuxtjs.org/docs/directory-structure/plugins
Solved by including #apollo/client and ts-invariant/process into the nuxt build transpile like so:
// nuxt.config.js
// ...
build: {
postcss: {
postcssOptions: require('./postcss.config.js')
},
transpile: [
'#apollo/client',
'ts-invariant/process',
],
},
// ...
I think I've pinpointed the underlying issue. Apollo Client (3.5.10 at the time of writing early 2022) is using "module":"index.js" to declare the path of the ESM exports.
However it seems that Webpack 5 based bundlers do not support this. Using exports in the package.json fixes it for good for me.
You should upvote this feature request.
And here is my palliative until then, using a small script to alter the package.json.
I'm new to the Typescript world and I'm facing an issue.
I'm trying to create a script to access firebase database functions, but when compiling the script I'm running into :
Uncaught ReferenceError: exports is not defined if I use "module": "commonjs" in my tsconfig.json
or
Uncaught SyntaxError: Cannot use import statement outside a module if I use "module": "es6"
In the second case, I can remove those three lines from the generated index.js file and everything is working properly :
import firebase from 'firebase/app';
import "firebase/database";
import "firebase/auth";
My question is, how can I use those external libraries in my typescript code, link them in my html without having those import in the compiled js file ?
Edit : Here's my ts file :
import firebase from 'firebase/app';
import "firebase/database"
import "firebase/auth"
class FbManager {
private static instance: FbManager;
firebaseConfig: object;
private constructor() {
this.firebaseConfig = {
...
};
firebase.initializeApp(this.firebaseConfig);
firebase.auth().onAuthStateChanged(function(user) {
console.log("AUTH STATE CHANGED");
if (user) {
console.log("LOGGED IN USER " + user.uid);
console.log(user);
} else {
console.log("SIGN OUT");
}
});
}
public static getInstance(): FbManager {
if (!FbManager.instance) {
FbManager.instance = new FbManager();
}
return FbManager.instance;
}
}
Thank you in advance !
Once you are in your repo type tsc --init after that TS config file will be generated.
Go to this file and uncomment outDir and after semicolon write e.g. "./build". Whole line will look like this "outDir": "./build"
Next thing you can do is to go to your package.json and in scripts write build: tsc. You'll be able to run npm command which will build your .ts files in build directory.
I was trying to access the commercejs Library's Public Key in React. But i failed to do so and met with this error. I can't understand why i am getting this error.
src\lib\commerce.js
import Commerce from '#chec/commerce.js';
export const commerce = new Commerce(process.env.REACT_APP_CHEC_PUBLIC_KEY, true);
src\App.js
import React, {useState, useEffect} from 'react';
import {Products, Navbar} from './components';
import {commerce} from './lib/commerce';
const App = () => {
const [products, setProducts] = useState([]);
const fetchProducts = async () => {
const {data} = await commerce.products.list();
setProducts(data);
}
useEffect(() => {
fetchProducts();
})
console.log(products);
return (
<div>
<Navbar/>
<Products/>
</div>
)
}
export default App;
Error
TypeError: t is undefined
e
node_modules/#chec/commerce.js/lib/index.js:1
Ah, I see you're a man of culture as well, watching Javascript Mastery on Youtube!
Just check where you created the .env file. It should be stored in the root folder. I had it in my src folder that's how I got this error. If it doesn't work, then go to your commercejs client, login and then at your settings, refresh your PUBLIC API. When you get a new one, just replace it. It should work after this.
Robbie from Commerce.js here. We've had a number of issues from people following this tutorial, so here are a couple of things to watch out for:
Make sure your .env file is in your project's root folder (the same folder that your package.json file is in)
Ensure you have installed the dotenv package. You can make sure by running npm install dotenv or yarn add dotenv.
Put your public key in your .env file under the REACT_APP_CHEC_PUBLIC_KEY variable and ensure that your API key is valid. You can fetch your valid API keys from the Chec Dashboard.
Restart your local dev server after making changes to your .env file.
Hope this helps 👋
I got to same error. You should write terminal npm install #chec/commerce.js and npm install -g #chec/cli or visit the website commerce.js => "https://dashboard.chec.io/" .
I also face this issue when I watching Javascript Mastery on Youtube. What I did was, disconnect the connection with .env file and just add the public key to commerce.js.This is not the best practice.
export const commerce = new Commerce("Your public key", true);
I'm trying to learn nativescript-vue where I'm using the Nativescript's Playground to tryout my sample codes. I'm trying to use nativescript-localstorage package so that I can store some of the information into local storage:
Whenever I'm trying to save project it is giving use compilation error
and following is the error:
An error occurred while transpiling nativescript-localstorage/localstorage.js.
unknown: We found a path that isn't a NodePath instance. Possiblly due to bad serialisation.
I followed the tutorials and added the package as it was instructed my code looks like:
import Vue from 'nativescript-vue';
import Vuex from 'vuex';
import localStorage from 'nativescript-localstorage';
import userStore from './user-store';
//For local storage of vuex tools
const NSVuexPersistent = store => {
// Init hook.
let storageStr = localStorage.getItem('ns-vuex-persistent');
if (storageStr) {
store.replaceState(JSON.parse(storageStr))
}
store.subscribe((mutation, state) => {
// Subscribe hook.
localStorage.setItem('ns-vuex-persistent', JSON.stringify(state));
})
};
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production';
export default new Vuex.Store({
modules: {
userStore
},
strict: debug,
plugins: [NSVuexPersistent]
})
Since the project is not getting saved so I've not shared the link. Help me out with it. Thanks.
nativescript-vue is packaged within the Preview APK, so it can be imported as
import Vue from 'nativescript-vue'
But nativescript-localstorage is something you have installed in your project, so while at Playground you should use relative path to import the module, something like
import * as localStorage from "../nativescript-localstorage"
// Or
const localStorage = require("../nativescript-localstorage");
You can use import name from "package" only when the package has marked something as default in its exports, the syntax is commonly used in ES6 & Vue plugins. nativescript-localstorage has not exported anything as default.
I'm trying to decode my token with jwt-decode but I can't. It gives me the following error. Does anyone know why?
ERROR Error: Uncaught (in promise): TypeError: jwt_decode_1.default is
not a function TypeError: jwt_decode_1.default is not a function
at RoleGuardService.canActivate (role-guard.service.ts?d7c4:19)
import jwt_decode from 'jwt-decode';
canActivate(route: ActivatedRouteSnapshot): boolean {
// this will be passed from the route config
// on the data property
const expectedRole = route.data.expectedRole;
const token = localStorage.getItem('token');
// decode the token to get its payload
const tokenPayload = jwt_decode(token);
console.log(tokenPayload);
if (
!this.auth.isAuthenticated() ||
tokenPayload.role !== expectedRole
) {
this.router.navigate(['login']);
return false;
}
return true;
}
I think you should import it like this:
import * as jwt_decode from 'jwt-decode';
According to documentation + internet search, the correct way is:
1. Install the package + types
npm install --save jwt-decode
npm install --save #types/jwt-decode
When you import the jwt_decode, you should surpass a rule from tslint, your code will look exactly like this (with commented line above)
// #ts-ignore
import jwt_decode from "jwt-decode";
Otherwise you will get an error like this
You can add also the rule for that on tsconfig.json , but is 1 time exception :)
I had the same error but after many attempts I did manage to solve this problem by using another method:
private decode(token: string) {
try {
return JSON.parse(atob(token.split(".")[1]));
} catch (e) {
console.log("error decoding token");
}
}
function atob() references
jwt_decode has always been a CommonJS module which generally are imported as const jwt_decode = require('jwt-decode');, it's what Node.js uses.
The way to import CommonJS libraries with a JS import statement is import * as library-name from 'library-name;.
Modern frameworks like Angular 10 throw a warning when using packages with the CommonJS format, because they generally speaking can't be tree-shaked.
Version 3 (now in beta) of this library includes a more modern ESM build, which is what JS import statements are meant for, so importing the modern ESM package can be done the regular way using import jwt_decode from 'jwt-decode';. This is a breaking change, that's why I've created a new major version 3.
We still have a CommonJS build, but by default most modern build systems for the web (not node) will use the ESM build.
if you checkout the package.json file when installing the lib, you'll notice both builds in there.
{
...
"main": "build/jwt-decode.cjs.js",
"module": "build/jwt-decode.esm.js",
...
}
references
npm install --legacy-peer-deps
npm install --save jwt-decode
npm install --save #types/jwt-decode
This solves mine problem
reference