Error: Cannot find module 'styled-jsx/style'
Link to the code that reproduces this issue
https://github.com/jmarroyave-compsci/error-nextjs-netlify-styled-jsx
To Reproduce
- When deploying a build to netlify after upgrading Next.js from 12.3.4 to 13.5.5
- When trying to fetch an api handler from the browser it shows the error ( /pages/api folder )
- Happens also in versions: 13.5.5-canary.8, 13.5.4, 13.5.3, 13.0.0
Current vs. Expected behavior
Expect to fetch data from API's handler but instead shows the errror
Verify canary release
- [X] I verified that the issue exists in the latest Next.js canary release
Provide environment information
Binaries:
Node: v16.20.0
npm: 8.19.4
Which area(s) are affected? (Select all that apply)
Middleware / Edge (API routes, runtime)
Additional context
What I tried?
Installing different plugin versions ( @netlify/plugin-nextjs )
Installing different nextjs versions
Deleting node_modules and package-lock.json and reinstalling everything again
npm i -S styled-jsx
I don't understand why this gets no response from Next team. Ive had an issue open with similar things happening on API routes since the release of 13.5 on Sept. 20.
In our project we had a old hack related to an issues with [...slug]
App.getInitialProps = async ({ router: _ }) => {
//hack to get router.asPath to work with [...slug], with out this it don't return the url but only the acutal url inside next.js
return {
props: {}, // will be passed to the page component as props
}
}
Removing this fixed it in our case, so maybe you should have look if you have any getInitialProps etc that could cause it.
In our project we had a old hack related to an issues with [...slug]
App.getInitialProps = async ({ router: _ }) => { //hack to get router.asPath to work with [...slug], with out this it don't return the url but only the acutal url inside next.js return { props: {}, // will be passed to the page component as props } }Removing this fixed it in our case, so maybe you should have look if you have any getInitialProps etc that could cause it.
Pages work fine, this is specifically with API routes for me ^
I confirm it is solved in version 14.0.1
having same issue on standalone build for 15.0.3
I have the same issue with 14.2.21. When running in localhost works just fine. But when deploying to Vercel then I get this error for my only nodejs api endpoint. The Edge runtime endpoints seem to work.
Cannot find module 'styled-jsx/style'
Require stack:
- /var/task/node_modules/next/dist/compiled/next-server/server.runtime.prod.js
- /var/task/___next_launcher.cjs
Did you forget to add it to "dependencies" in `package.json`?
Node.js process exited with exit status: 1. The logs above can help with debugging the issue.
I had this exact error message when linting in a Github action, but my issue was that the key I was using for my cache was incorrectly set. I was trying to hash a file that didn't exist for the cache key. So my ci cache wasn't being refreshed correctly. Might be something to check for others.
I have the same error. Upgrading next to 15 from 14 works for me.
v15.2.4 still has this issue
Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!
I have the same issue on Next 15
Edit by maintainer bot: Comment was automatically minimized because it was considered unhelpful. (If you think this was by mistake, let us know). Please only comment if it adds context to the issue. If you want to express that you have the same problem, use the upvote 👍 on the issue description or subscribe to the issue for updates. Thanks!
For everyone wondering about it.. I drafted a solution that works for my usecase - The error - "Error: Cannot find module 'styled-jsx/package.json" happened in my case because of pnpm symlinks style. I ended up writing a script that eliminates and hard copies symlinks inside the standalone node_modules folder, and also moving all node modules under .pnpm/.../node_modules/... up, essentially lifting it up to standalone/node_modules level. it resolves the issues for me.
Hope it helps - happy coding 👍
#!/usr/bin/env node
/**
* This script lifts all modules from the .pnpm leaf node_modules directories
* to the root node_modules directory in the standalone output.
* It preserves the folder structure and handles symlinks by copying them as hard copies.
*/
const path = require('path');
const fs = require('fs-extra');
// Path to the standalone output directory
const standaloneDir = path.join(__dirname, '.next', 'standalone');
const nodeModulesDir = path.join(standaloneDir, 'node_modules');
const pnpmDir = path.join(nodeModulesDir, '.pnpm');
/**
* Recursively converts all symlinks in a directory to hard copies
* @param {string} dirPath - The directory path to process
*/
async function convertSymlinksToHardCopies(dirPath, isRoot = false) {
// Get all items in the directory
const items = await fs.readdir(dirPath);
for (const item of items) {
// Skip .pnpm directory in root node_modules it is taken care of at liftModulesFromPnpm
if (isRoot && item === '.pnpm') continue;
const itemPath = path.join(dirPath, item);
const stats = await fs.lstat(itemPath);
if (stats.isSymbolicLink()) {
// Get the target of the symlink
const targetPath = await fs.readlink(itemPath);
const resolvedTargetPath = path.resolve(dirPath, targetPath);
if (!fs.existsSync(targetPath)) {
console.error(`Target does not exist: ${targetPath}`);
fs.removeSync(itemPath);
}
// Copy the target to the original symlink location
if ((await fs.stat(resolvedTargetPath)).isDirectory()) {
await fs.copy(resolvedTargetPath, itemPath, {
dereference: true,
overwrite: true,
errorOnExist: false,
});
} else {
await fs.copyFile(resolvedTargetPath, itemPath, {
dereference: true,
overwrite: true,
errorOnExist: false,
});
}
} else if (stats.isDirectory()) {
// Recursively process subdirectories
await convertSymlinksToHardCopies(itemPath, true);
}
}
}
/**
* Processes .pnpm directories and lifts up their node_modules to the root node_modules
*/
const liftModulesFromPnpm = () => {
// Check if .pnpm directory exists
if (!fs.existsSync(pnpmDir)) {
console.error(`.pnpm directory not found at ${pnpmDir}`);
return;
}
// Get all directories in the .pnpm directory
const pnpmDirs = fs
.readdirSync(pnpmDir)
.filter((dir) => fs.statSync(path.join(pnpmDir, dir)).isDirectory());
console.log(`Found ${pnpmDirs.length} package directories in .pnpm`);
// Process each .pnpm package directory
for (const pnpmPkgDir of pnpmDirs) {
const pnpmPkgPath = path.join(pnpmDir, pnpmPkgDir);
let nodeModulesInPnpm = pnpmPkgPath;
// Stupid edgecase has .pnpm/X/node_modules/<node_modules> but also .pnpm/node_modules/<node_modules>
if (!nodeModulesInPnpm.endsWith('node_modules')) {
nodeModulesInPnpm = path.join(pnpmPkgPath, 'node_modules');
}
// Get all modules in this package's node_modules
const moduleDirs = fs.readdirSync(nodeModulesInPnpm);
// Copy each module to the root node_modules
for (const moduleDirOrFile of moduleDirs) {
const sourcePath = path.join(nodeModulesInPnpm, moduleDirOrFile);
const destPath = path.join(nodeModulesDir, moduleDirOrFile);
// Check if destination already exists
if (fs.existsSync(destPath)) {
if (!fs.statSync(destPath).isDirectory()) {
continue;
}
if (!fs.statSync(sourcePath).isDirectory()) {
throw new Error(
`very wierd - dest is a directory but source is not [source: ${sourcePath}, dest: ${destPath}]`,
);
}
for (const subModuleDirOrFile of fs.readdirSync(sourcePath)) {
const subSourcePath = path.join(sourcePath, subModuleDirOrFile);
const subDestPath = path.join(destPath, subModuleDirOrFile);
if (fs.existsSync(subDestPath)) {
continue;
}
// Copy sub directory with all contents, resolving symlinks to real files
fs.copySync(subSourcePath, subDestPath, {
overwrite: false,
dereference: true, // Convert symlinks to actual files/directories
errorOnExist: false, // Don't error if destination exists
});
}
continue;
}
// Copy directory with all contents, resolving symlinks to real files
fs.copySync(sourcePath, destPath, {
overwrite: false,
dereference: true, // Convert symlinks to actual files/directories
errorOnExist: false, // Don't error if destination exists
});
}
}
};
// Main function
const main = async () => {
// console.log('Starting to lift modules from .pnpm to root node_modules...');
if (!fs.existsSync(standaloneDir)) {
// console.error(`Standalone directory not found: ${standaloneDir}`);
process.exit(1);
}
if (!fs.existsSync(nodeModulesDir)) {
// console.error(`node_modules directory not found: ${nodeModulesDir}`);
process.exit(1);
}
console.log('Converting symlinks to hard copies recursively...');
await convertSymlinksToHardCopies(nodeModulesDir);
console.log('Finished converting symlinks to hard copies.');
console.log('Lifting modules from .pnpm to root node_modules...');
liftModulesFromPnpm();
console.log('Finished lifting modules from .pnpm to root node_modules.');
console.log('Removing .pnpm directory...');
fs.removeSync(pnpmDir);
console.log('Finished removing .pnpm directory.');
};
// Run the script
main();
For everyone wondering about it.. I drafted a solution that works for my usecase - The error - "Error: Cannot find module 'styled-jsx/package.json" happened in my case because of pnpm symlinks style. I ended up writing a script that eliminates and hard copies symlinks inside the standalone node_modules folder, and also moving all node modules under .pnpm/.../node_modules/... up, essentially lifting it up to standalone/node_modules level. it resolves the issues for me.
Hope it helps - happy coding 👍
#!/usr/bin/env node /** * This script lifts all modules from the .pnpm leaf node_modules directories * to the root node_modules directory in the standalone output. * It preserves the folder structure and handles symlinks by copying them as hard copies. */ const path = require('path'); const fs = require('fs-extra'); // Path to the standalone output directory const standaloneDir = path.join(__dirname, '.next', 'standalone'); const nodeModulesDir = path.join(standaloneDir, 'node_modules'); const pnpmDir = path.join(nodeModulesDir, '.pnpm'); /** * Recursively converts all symlinks in a directory to hard copies * @param {string} dirPath - The directory path to process */ async function convertSymlinksToHardCopies(dirPath, isRoot = false) { // Get all items in the directory const items = await fs.readdir(dirPath); for (const item of items) { // Skip .pnpm directory in root node_modules it is taken care of at liftModulesFromPnpm if (isRoot && item === '.pnpm') continue; const itemPath = path.join(dirPath, item); const stats = await fs.lstat(itemPath); if (stats.isSymbolicLink()) { // Get the target of the symlink const targetPath = await fs.readlink(itemPath); const resolvedTargetPath = path.resolve(dirPath, targetPath); if (!fs.existsSync(targetPath)) { console.error(`Target does not exist: ${targetPath}`); fs.removeSync(itemPath); } // Copy the target to the original symlink location if ((await fs.stat(resolvedTargetPath)).isDirectory()) { await fs.copy(resolvedTargetPath, itemPath, { dereference: true, overwrite: true, errorOnExist: false, }); } else { await fs.copyFile(resolvedTargetPath, itemPath, { dereference: true, overwrite: true, errorOnExist: false, }); } } else if (stats.isDirectory()) { // Recursively process subdirectories await convertSymlinksToHardCopies(itemPath, true); } } } /** * Processes .pnpm directories and lifts up their node_modules to the root node_modules */ const liftModulesFromPnpm = () => { // Check if .pnpm directory exists if (!fs.existsSync(pnpmDir)) { console.error(`.pnpm directory not found at ${pnpmDir}`); return; } // Get all directories in the .pnpm directory const pnpmDirs = fs .readdirSync(pnpmDir) .filter((dir) => fs.statSync(path.join(pnpmDir, dir)).isDirectory()); console.log(`Found ${pnpmDirs.length} package directories in .pnpm`); // Process each .pnpm package directory for (const pnpmPkgDir of pnpmDirs) { const pnpmPkgPath = path.join(pnpmDir, pnpmPkgDir); let nodeModulesInPnpm = pnpmPkgPath; // Stupid edgecase has .pnpm/X/node_modules/<node_modules> but also .pnpm/node_modules/<node_modules> if (!nodeModulesInPnpm.endsWith('node_modules')) { nodeModulesInPnpm = path.join(pnpmPkgPath, 'node_modules'); } // Get all modules in this package's node_modules const moduleDirs = fs.readdirSync(nodeModulesInPnpm); // Copy each module to the root node_modules for (const moduleDirOrFile of moduleDirs) { const sourcePath = path.join(nodeModulesInPnpm, moduleDirOrFile); const destPath = path.join(nodeModulesDir, moduleDirOrFile); // Check if destination already exists if (fs.existsSync(destPath)) { if (!fs.statSync(destPath).isDirectory()) { continue; } if (!fs.statSync(sourcePath).isDirectory()) { throw new Error( `very wierd - dest is a directory but source is not [source: ${sourcePath}, dest: ${destPath}]`, ); } for (const subModuleDirOrFile of fs.readdirSync(sourcePath)) { const subSourcePath = path.join(sourcePath, subModuleDirOrFile); const subDestPath = path.join(destPath, subModuleDirOrFile); if (fs.existsSync(subDestPath)) { continue; } // Copy sub directory with all contents, resolving symlinks to real files fs.copySync(subSourcePath, subDestPath, { overwrite: false, dereference: true, // Convert symlinks to actual files/directories errorOnExist: false, // Don't error if destination exists }); } continue; } // Copy directory with all contents, resolving symlinks to real files fs.copySync(sourcePath, destPath, { overwrite: false, dereference: true, // Convert symlinks to actual files/directories errorOnExist: false, // Don't error if destination exists }); } } }; // Main function const main = async () => { // console.log('Starting to lift modules from .pnpm to root node_modules...'); if (!fs.existsSync(standaloneDir)) { // console.error(`Standalone directory not found: ${standaloneDir}`); process.exit(1); } if (!fs.existsSync(nodeModulesDir)) { // console.error(`node_modules directory not found: ${nodeModulesDir}`); process.exit(1); } console.log('Converting symlinks to hard copies recursively...'); await convertSymlinksToHardCopies(nodeModulesDir); console.log('Finished converting symlinks to hard copies.'); console.log('Lifting modules from .pnpm to root node_modules...'); liftModulesFromPnpm(); console.log('Finished lifting modules from .pnpm to root node_modules.'); console.log('Removing .pnpm directory...'); fs.removeSync(pnpmDir); console.log('Finished removing .pnpm directory.'); }; // Run the script main();
Thanks @omerman! This solution worked for me!
@omerman I was able to solve it by just setting this in pnpm-workspace.yaml:
publicHoistPattern:
- 'styled-jsx'
This tells pnpm to hoist the package so that it sits in the top-level of node_modules. Next.js must rely on this being the case.