Beginner - Next JS. 'fs' module not found issue. #12124
-
I am going through the blog tutorial on Next JS site, and encountered this error when trying to implement static rendering.
|
Beta Was this translation helpful? Give feedback.
Replies: 13 comments 25 replies
-
Welcome! import fs from 'fs';
export default function Home(props) {
return (
<div className="container">
...
</div>
);
}
// getStaticProps only runs in the Node side, so it is safe
// to use libraries from Node here
export async function getStaticProps() {
const fileNames = fs.readdirSync(postsDirectory);
...
} In the tutorial these libraries are imported in another file, but a bit later they are utilized inside export async function getStaticProps() {
const allPostsData = getSortedPostsData()
return {
props: {
allPostsData
}
}
} |
Beta Was this translation helpful? Give feedback.
-
I'm not sure what I'm doing incorrectly. The sample does work, but when I try to write my own component, I get the error: import { promises } from 'fs'
import React from 'react'
import { join } from 'path'
import firebase from '../utils/firebase'
// Configure FirebaseUI.
const uiConfig = {
// Redirect to /signedIn after sign in is successful. Alternatively you can provide a callbacks.signInSuccess function.
signInSuccessUrl: '/signedIn',
// We will display Google and Facebook as auth providers.
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.EmailAuthProvider.PROVIDER_ID,
]
}
export default function LoginOptions ({ css }) {
React.useEffect(() => {
// must be required here since this is client-side rendered
const firebaseui = require('firebaseui')
// Initialize the FirebaseUI Widget using Firebase.
const ui = new firebaseui.auth.AuthUI(firebase.auth())
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
}, [])
return (
<>
<div id="firebaseui-auth-container"></div>
<style jsx global>{css}</style>
</>
)
}
export async function getStaticProps () {
const css = await promises.readFile(join(process.cwd(), 'public', 'firebaseui.css'))
return {
props: {
css
}
}
} |
Beta Was this translation helpful? Give feedback.
-
i'm getting this error by just adding an
|
Beta Was this translation helpful? Give feedback.
-
Now, I create a TS file just for typing. It's actually this, and it throws error. It does not ignore import fs from 'fs'
import yaml from 'js-yaml'
import path from 'path'
import * as z from 'zod'
export const zRemark42 = () => z.object({
host: z.string(),
siteId: z.string(),
locale: z.string().optional()
})
export type IRemark42 = z.infer<ReturnType<typeof zRemark42>>
export const zAuthor = () => z.object({
name: z.string(),
email: z.string().optional(),
url: z.string().optional()
})
export type IAuthor = z.infer<ReturnType<typeof zAuthor>>
export const zTabs = () => z.array(z.object({
name: z.string(),
to: z.string().optional(),
href: z.string().optional()
}))
export type ITabs = z.infer<ReturnType<typeof zTabs>>
export const zSidebar = () => z.object({
twitter: z.string().optional(),
tagCloud: z.object({
excluded: z.array(z.string()).optional()
}).optional()
})
export type ISidebar = z.infer<ReturnType<typeof zSidebar>>
export const zSocial = () => z.object({
twitter: z.string().optional(),
reddit: z.string().optional(),
quora: z.string().optional(),
github: z.string().optional()
})
export type ISocial = z.infer<ReturnType<typeof zSocial>>
export const zTheme = () => z.object({
title: z.string(),
banner: z.string().optional(),
baseUrl: z.string().optional(),
description: z.string().optional(),
keywords: z.array(z.string()).optional(),
tabs: zTabs().optional(),
author: zAuthor(),
social: zSocial().optional(),
sidebar: zSidebar().optional(),
analytics: z.object({
plausible: z.string().optional()
}).optional(),
comments: z.object({
remark42: zRemark42().optional()
}).optional()
})
export const getTheme = () => zTheme().parse(yaml.safeLoad(fs.readFileSync(path.join(__dirname, '../theme.yml'), 'utf8')))
export type ITheme = z.infer<ReturnType<typeof zTheme>> |
Beta Was this translation helpful? Give feedback.
-
it seems that I cannot use fs event in getStaticProps, the compiler renders an error just when importing fs, even if it's not used at all.. |
Beta Was this translation helpful? Give feedback.
-
I made this way: import path from 'path';
function HomePage(props) {
const { products, filePath } = props;
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.title}</li>
))}
</ul>
);
}
export async function getStaticProps(context) {
const fs = require('fs/promises'); // LOOK HERE
const filePath = path.join(process.cwd(), 'data', 'dummy-data.json');
const fileData = await fs.readFile(filePath);
const data = JSON.parse(fileData);
return {
props: {
products: data.products,
},
};
}
export default HomePage; |
Beta Was this translation helpful? Give feedback.
-
I had the same issue, apparently the issue is that
I learned this from this article, where someone had the same issue |
Beta Was this translation helpful? Give feedback.
-
To those who might not find a solution in the answers above Verify your It needs to be as written below import "../styles/global.css";
export default function App({ Component, pageProps }) {
return <Component {...pageProps} />;
} NOT like this import "../styles/global.css";
export default function App({ Component }, { pageProps }) {
return <Component {...pageProps} />;
} which was my problem, in this example |
Beta Was this translation helpful? Give feedback.
-
i had the same issue and i fixed it by |
Beta Was this translation helpful? Give feedback.
-
After figuring out for 2 hours finally It resolved. I faced the issue because of wrong function name. Instead of
Check properly the name of functions. |
Beta Was this translation helpful? Give feedback.
-
Hi Team, How can I writeJsonFile in next.js / react ? |
Beta Was this translation helpful? Give feedback.
-
Don't use You could put the util file which uses Then // /pages/myPage/index.tsx
import View from './view';
export default View;
export async function getStaticProps() {
const util = require('core/some-util-uses-fs').default; // getStaticProps runs in nodes
const data = await util.getDataFromDisk();
return {
props: {
data,
},
};
} |
Beta Was this translation helpful? Give feedback.
-
I'm using winston for logging at server side, and toast utility at client side, tried a dynamic import of winston, and file where logger is implemented, but its still giving fs error, tried |
Beta Was this translation helpful? Give feedback.
Welcome!
fs
is a library exclusive to Node, so you can't use it directly in the browser. But if you import it at the top of the file and use it in a function that only runs in the server, then Next will remove this import from the client bundle, so this code is valid:In the tutorial these libraries are imported in another file, but a bit later they are utilized ins…