import nookies from 'nookies';
import { firebaseAdmin } from "../firebaseAdmin";
import { TChildren } from "../types/app/app.types";
interface Props {
children: TChildren;
}
export default function ProtectedRoute(props: Props): JSX.Element {
return <>
{props.children}
</>
}
export const getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const cookies = nookies.get(ctx);
const data = await firebaseAdmin.auth().verifyIdToken(cookies.token);
console.log(data);
return {
props: { message: `Your email is .` },
};
};
await firebaseAdmin.auth().verifyIdToken throws error module not found: can't resolve fs, How to fix this error?
I know that we have different types of runtime environments like edge, browser nodeJs, but based of the docs and examples getServerSide Props runs on nodeJs environment which means that I shouldn't get this kind of error...
Is the 'fs' module available in the environment?
npm i fs-extra
Then using commonjs:
const fs = require('fs-extra')
OR using latest es6 module system:
import fs from 'fs-extra'
Related
I created a React app and I try to make a separate file for functions.
I required 'jwt-decode' library like that:
const jwt_decode = require("jwt-decode");
After that I used it like that:
const verifyToken = (token) => { console.log(jwt_decode(token)); };
And exported like that:
module.exports = { verifyToken };
When I tried to use it in my react page, I saw this error in the console:
Uncaught TypeError: jwt_decode is not a function
What I did wrong?
You need to require the default export:
const { default: jwt_decode } = require("jwt-decode");
const token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
console.log(jwt_decode(token));
Expected output:
{ sub: '1234567890', name: 'John Doe', iat: 1516239022 }
Alternatively use import when type in package.json is set to module.
import jwt_decode from "jwt-decode";
It looks like you are trying to use CommonJS require syntax in a React app that is likely using ES6 import syntax.
Try changing your code to the following:
import jwt_decode from "jwt-decode";
const verifyToken = (token) => { console.log(jwt_decode(token)); };
export default { verifyToken };
And then in your React page, use:
import verifyToken from './path/to/your/file';
It works to me!
import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const mdxToJsx = async (value) => {
const { default: Content } = await run(value, runtime);
return Content
};
export default mdxToJsx;
Here as per mdx library, I want to convert mdx to jsx but I got Uncaught (in promise) SyntaxError: Unexpected identifier 'Promise'
at new AsyncFunction ()
at run (run.js:15:1)
Kindly help me. Thanks Happy coding.
import React, { Fragment, useEffect, useState } from "react";
import { run } from "#mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
export default function MdxToJsx({code}) {
const [mdxModule, setMdxModule] = useState()
const Content = mdxModule ? mdxModule.default : Fragment
useEffect(() => {
(async () => {
setMdxModule(await run(code, runtime))
})()
}, [code])
return <Content />
}
I tried this one also but got the same error.
I made an npm module, this module export a function that load a json file and then export the result ( a little bit simplified )
The probleme is when I import this module inside another project I have this error :
no such file or directory, open 'C:\Users\{my_username}\github\{name_of_the_project}\file.json'
I looks like when I import my module, it try to read the json inside the current directory and not inside the npm module.
The code inside my module :
export default function() {
return readFile('./swagger.json')
.then(data => JSON.parse(data))
}
Final answer (for ES Module) :
import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import path from 'path';
export default function() {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
return readFile(`${__dirname}/swagger.json`)
.then(data => JSON.parse(data))
}
If you don't use ES Module (but commonJS), __dirname already exist so you can do :
export default function() {
return readFile(`${__dirname}/swagger.json`)
.then(data => JSON.parse(data))
}
I am struggling with migrating firebase v8 -> v9. I have a component library with Storybook for demoing components. This library is published as a package through NPM/Github packages.
The migration have not given me any trouble, except this. The problem occurs when importing and using the component below in my web app.
The code below works perfectly in Storybook, but fails when importing the component into my web app.
const useGetLanguages = (firestoreInstance: Firestore): Response => {
const [loading, setLoading] = useState(false)
const [data, setData] = useState<ILanguage[]>([])
console.log('firestoreInstance: ', firestoreInstance) // Logs firestore instance
const fetch = useCallback(() => {
if (!firestoreInstance) return
setLoading(true)
const collectionRef = collection(firestoreInstance, 'data')
console.log('blip') // this logs fine
getDoc(doc(collectionRef, 'tags')) // crashes here...
.then(res => {
const data = res?.data()?.languages
if (data) {
const languages = (Object.values(data) as unknown) as ILanguage[]
if (languages) {
setData(languages.sort(sortBy('name')))
}
}
})
.finally(() => {
setLoading(false)
})
}, [firestoreInstance])
I initially used:
getDoc(doc(firestoreInstance, 'data', 'tags'))
which also worked in Storybook, but when navigating to a page using this hook in my web app, I get this error:
Uncaught FirebaseError: Expected first argument to collection() to be a CollectionReference,
a DocumentReference or FirebaseFirestore
I have read through similar questions, but it does not solve the issue. Any input would be much appreciated!
EDIT: I am importing firebase like this:
// firebaseConfig.ts
import { FirebaseOptions, initializeApp } from 'firebase/app'
import { getAuth } from 'firebase/auth'
import { getFirestore } from 'firebase/firestore'
import { getFunctions } from 'firebase/functions'
const config: FirebaseOptions = {
// ...config
}
export const app = initializeApp(firebaseConfig)
export const authInstance = getAuth(app)
export const firestoreInstance = getFirestore(app)
export const functionsInstance = getFunctions(app)
I then import firestoreInstance and pass it to the function/component that is imported from the package.
I will try to pass the config itself and consume that in the package and post result.
It turned out to be a slip up from our side. We needed to install firebase as a peerDependency in our package.json. Had similar issues when migrating to MUI 5. If anyone else is getting obscure errors that do not make sense in your situation it might be worth a shot to check where you have your dependencies!
I am trying to write some unit tests and I am getting errors in the test and I am trying to understand why the errors happen.
The unit test is for the index.ts file that calls the features/index.ts file. I am stubbing the default export from features/index.ts with sinon. But when I run the tests I get the following error TypeError: Cannot read property 'resolve' of undefined pointing at the file features/feature1.ts
I have added the relavant extracts from the tests and typescript files below.
features/feature1.ts
import path from "path";
import fs from "fs";
import {Setup} from "../types";
const TEMPLATE_ROOT = path.resolve(__dirname,"../../templates");
const INDEX_TEMPLATE = fs.readFileSync(TEMPLATE_ROOT, "index.js"), "utf8");
export const setup: Setup = async ({config, options}) => {
// Internal code removed
}
features/index.ts
import {setup as feature1} from "./feature1.ts";
import {setup as feature2} from "./feature2.ts";
type FeatureTypes = "feature1" | "feature2"
type Features = {
[key in FeatureTypes]: Setup;
};
const features: Features = {
feature1: feature1,
feature2: feature2
}
export default features
index.ts
import features from "./features"
import { Config, Options } from "./types";
export async function init(config: Config, options: Options): Promise<void> {
const nextFeature = options.features ? options.features.shift() : undefined;
if (nextFeature) {
// Other irrelevant code
await Promise.resolve(features[nextFeature]({ config, options }));
return init(config, options);
}
}
index.spec.ts
import { expect } from "chai";
import * as sinon from "sinon";
import { init } from '.'
import * as features from "./features";
import { Config, Options } from "./types"
describe("init", () => {
const sandbox: sinon.SinonSandbox = sinon.createSandbox();
let featuresStub: sinon.SinonStub;
beforeEach(() => {
featuresStub = sandbox.stub(features, "default").returns({
feature1: sandbox.stub().resolves(),
feature2: sandbox.stub().resolves(),
});
});
afterEach(() => {
sandbox.restore();
});
it("should call setup features", async () => {
const setup: Setup = {
features: [
"feature1",
"feature2",
],
};
await init({}, options);
expect(featuresStub).to.have.been.calledOnce;
});
// rest of tests
});
I have also tried the changing the stub setup to be:
import * as feature1 from ".features/feature1";
import * as feature2 from ".features/feature2";
// Other code
describe("init", () => {
const sandbox: sinon.SinonSandbox = sinon.createSandbox();
let feature1Stub: sinon.SinonStub;
let feature2Stub: sinon.SinonStub;
beforeEach(() => {
feature1Stub = sandbox.stub(feature1, "setup");
feature2Stub = sandbox.stub(feature2, "setup");
feature1Stub.resolves()
feature2Stub.resolves()
});
// Rest of code and tests
});
I don't know why it would be trying to run code const TEMPLATE_ROOT = path.resolve(__dirname,"../../templates"); if I have stubbed the function that calls it.
Figured it out the imports were wrong
import path from "path";
import fs from "fs";
should be:
import * as path from "path";
import * as fs from "fs";