netlify / next-runtime

The Next.js Runtime allows Next.js to run on Netlify with zero configuration
https://www.npmjs.com/package/@netlify/plugin-nextjs
638 stars 85 forks source link

[Bug]: Cannot find module 'styled-jsx/style' #2330

Closed skordesign closed 11 months ago

skordesign commented 11 months ago

Summary

The issue happened when I integrated Builder.io into Nextjs and deployed it to Netlify. It works fine when I deploy to a VPS. image

A link to a reproduction repository

https://github.com/skordesign/next-builder-io

Expected Result

Works fine

Actual Result

Show error Cannot find module 'styled-jsx/style'

Steps to reproduce

  1. Create a new Next App Router project
  2. Integrated with Builder.io follow https://www.builder.io/c/docs/integrating-builder-pages
  3. Deploy to Netlify using ntl command

Next Runtime version

4.40.2

Is your issue related to the app directory?

More information about your build

What OS are you using?

Windows

Your netlify.toml file

`netlify.toml` ```toml # example netlify.toml [build] command = "npm run build" functions = "netlify/functions" publish = ".next" ## Uncomment to use this redirect for Single Page Applications like create-react-app. ## Not needed for static site generators. #[[redirects]] # from = "/*" # to = "/index.html" # status = 200 [[plugins]] package = "@netlify/plugin-nextjs" ## (optional) Settings for Netlify Dev ## https://github.com/netlify/cli/blob/main/docs/netlify-dev.md#project-detection #[dev] # command = "yarn start" # Command to start your dev server # port = 3000 # Port that the dev server will be listening on # publish = "dist" # Folder with the static content for _redirect file ## more info on configuring this file: https://docs.netlify.com/configure-builds/file-based-configuration/ ```

Your public/_redirects file

`_redirects` ``` # Paste content of your `_redirects` file here ```

Your next.config.js file

`next.config.js` ```js const withBuilderDevTools = require("@builder.io/dev-tools/next")(); /** @type {import('next').NextConfig} */ const nextConfig = withBuilderDevTools({}); module.exports = nextConfig; ```

Builds logs (or link to your logs)

Build logs ``` Netlify Build Version @netlify/build 29.22.5 Flags {} Current directory D:\Workspace\Code\Hegg\test-pages Config file D:\Workspace\Code\Hegg\test-pages\netlify.toml Context dev Using Next.js Runtime - v4.36.1 Outdated plugins - @netlify/plugin-nextjs@4.36.1: latest version is 4.40.1 Migration guide: https://ntl.fyi/next-plugin-migration To upgrade this plugin, please update its version in "package.json" @netlify/plugin-nextjs (onPreBuild event) Next.js cache restored. Netlify configuration property "build.environment.NEXT_PRIVATE_TARGET" value changed. (@netlify/plugin-nextjs onPreBuild completed in 4s) build.command from netlify.toml $ npm run build > test-pages@0.1.0 build > next build Creating an optimized production build ... Linting and checking validity of types ... ./src/app/[...page]/page.tsx 14:1 Warning: Prevent client components from being async functions. See: https://nextjs.org/docs/messages/no-async-client-component @next/next/no-async-client-component info - Need to disable some ESLint rules? Learn more here: https://nextjs.org/docs/basic-features/eslint#disabling-rules Collecting page data ... Generating static pages (0/6) ... Generating static pages (1/6) Generating static pages (2/6) Generating static pages (4/6) Γ£ô Generating static pages (6/6) Finalizing page optimization ... Collecting build traces ... Route (app) Size First Load JS / 344 B 86 kB /_not-found 883 B 81.4 kB /[...page] 57.7 kB 138 kB /test 348 B 86 kB + First Load JS shared by all 80.5 kB chunks/864-bd0ca5441cff7f3a.js 27.5 kB chunks/fd9d1056-24f21efd0722edc0.js 51 kB chunks/main-app-5956d7b770e81883.js 234 B chunks/webpack-f00c7c33c8ee7236.js 1.86 kB (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps) (Static) automatically rendered as static HTML (uses no initial props) (build.command completed in 13.1s) @netlify/plugin-nextjs (onBuild event) Patching D:\Workspace\Code\Hegg\test-pages\node_modules\next\dist\server\base-server.js Done Patching D:\Workspace\Code\Hegg\test-pages\node_modules\next\dist\server\next-server.js Done Moving static page files to serve from CDN... Moved 6 files You are not using Netlify Edge Functions for image format detection. Set env var "NEXT_FORCE_EDGE_IMAGES=true" to enable. Netlify configuration property "redirects" value changed to [ { from: '/_next/static/*', to: '/static/:splat', status: 200 }, { from: '/_next/image*', query: { url: ':url', w: ':width', q: ':quality' }, to: '/_ipx/w_:width,q_:quality/:url', status: 301 }, { from: '/_ipx/*', to: '/.netlify/builders/_ipx', status: 200 }, { from: '/cache/*', to: '/404.html', status: 404, force: true }, { from: '/server/*', to: '/404.html', status: 404, force: true }, { from: '/serverless/*', to: '/404.html', status: 404, force: true }, { from: '/trace', to: '/404.html', status: 404, force: true }, { from: '/traces', to: '/404.html', status: 404, force: true }, { from: '/routes-manifest.json', to: '/404.html', status: 404, force: true }, { from: '/build-manifest.json', to: '/404.html', status: 404, force: true }, { from: '/prerender-manifest.json', to: '/404.html', status: 404, force: true }, { from: '/react-loadable-manifest.json', to: '/404.html', status: 404, force: true }, { from: '/BUILD_ID', to: '/404.html', status: 404, force: true }, { from: '/api/*', to: '/.netlify/functions/___netlify-handler', status: 200 }, { from: '/next.svg', to: '/next.svg', conditions: { Cookie: [Array] }, status: 200 }, { from: '/vercel.svg', to: '/vercel.svg', conditions: { Cookie: [Array] }, status: 200 }, { from: '/*', to: '/.netlify/functions/___netlify-handler', status: 200, conditions: { Cookie: [Array] }, force: true }, { from: '/_next/data/-CZLcvrM6st_YyeVW-_DC/_not-found.json', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/_not-found', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/_next/data/-CZLcvrM6st_YyeVW-_DC/:page/*', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/:page/*', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/*', to: '/.netlify/functions/___netlify-handler', status: 200 } ]. (@netlify/plugin-nextjs onBuild completed in 3.3s) Functions bundling The Netlify Functions setting targets a non-existing directory: netlify\functions Packaging Functions from .netlify\functions-internal directory: - _ipx\_ipx.js - ___netlify-handler\___netlify-handler.js - ___netlify-odb-handler\___netlify-odb-handler.js (Functions bundling completed in 16.4s) Edge Functions bundling Packaging Edge Functions from .netlify\edge-functions directory: - rsc-data (Edge Functions bundling completed in 987ms) @netlify/plugin-nextjs (onPostBuild event) Next.js cache saved. (@netlify/plugin-nextjs onPostBuild completed in 138ms) Netlify Build Complete (Netlify Build completed in 40.7s) 32mDeploy path: 39m D:\Workspace\Code\Hegg\test-pages\.next 32mFunctions path: 39m D:\Workspace\Code\Hegg\test-pages\netlify\functions 32mConfiguration path: 39mD:\Workspace\Code\Hegg\test-pages\netlify.toml Functions folder "D:\Workspace\Code\Hegg\test-pages\netlify\functions" specified but it doesn't exist! Will proceed without deploying functions Deploying to main site URL... 32mBuild logs: 39m https://app.netlify.com/sites/metaguest-pages/deploys/652924d534fba1268c7da6b4 32mFunction logs: 39m https://app.netlify.com/sites/metaguest-pages/functions 32mUnique deploy URL: 39mhttps://652924d534fba1268c7da6b4--metaguest-pages.netlify.app 32mWebsite URL: 39m https://metaguest-pages.netlify.app ```

Function logs

Function logs ``` Oct 13, 05:40:54 PM: INIT_START Runtime Version: nodejs:18.v13 Runtime Version ARN: arn:aws:lambda:us-east-2::runtime:0229ff5ced939264450549058d8f267110e92677c27063e6dcd781a280f2462bOct 13, 05:40:54 PM: 2023-10-13T10:40:54.911Z undefined ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'styled-jsx/style'\nRequire stack:\n- /var/task/node_modules/next/dist/server/require-hook.js\n- /var/task/node_modules/next/dist/server/next-server.js\n- /var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js\n- /var/task/___netlify-handler.js\n- /var/runtime/index.mjs","stack":["Runtime.ImportModuleError: Error: Cannot find module 'styled-jsx/style'","Require stack:","- /var/task/node_modules/next/dist/server/require-hook.js","- /var/task/node_modules/next/dist/server/next-server.js","- /var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js","- /var/task/___netlify-handler.js","- /var/runtime/index.mjs"," at _loadUserApp (file:///var/runtime/index.mjs:1061:17)"," at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)"," at async start (file:///var/runtime/index.mjs:1256:23)"," at async file:///var/runtime/index.mjs:1262:1"]}Oct 13, 05:40:54 PM: INIT_REPORT Init Duration: 129.70 ms Phase: init Status: error Error Type: Runtime.ExitErrorOct 13, 05:40:55 PM: 2023-10-13T10:40:55.359Z undefined ERROR Uncaught Exception {"errorType":"Runtime.ImportModuleError","errorMessage":"Error: Cannot find module 'styled-jsx/style'\nRequire stack:\n- /var/task/node_modules/next/dist/server/require-hook.js\n- /var/task/node_modules/next/dist/server/next-server.js\n- /var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js\n- /var/task/___netlify-handler.js\n- /var/runtime/index.mjs","stack":["Runtime.ImportModuleError: Error: Cannot find module 'styled-jsx/style'","Require stack:","- /var/task/node_modules/next/dist/server/require-hook.js","- /var/task/node_modules/next/dist/server/next-server.js","- /var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js","- /var/task/___netlify-handler.js","- /var/runtime/index.mjs"," at _loadUserApp (file:///var/runtime/index.mjs:1061:17)"," at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)"," at async start (file:///var/runtime/index.mjs:1256:23)"," at async file:///var/runtime/index.mjs:1262:1"]}Oct 13, 05:40:55 PM: INIT_REPORT Init Duration: 229.16 ms Phase: invoke Status: error Error Type: Runtime.ExitErrorOct 13, 05:40:55 PM: Unknown application error occurred Runtime.ImportModuleErrorOct 13, 05:40:55 PM: 7c3f74fd Duration: 229.82 ms Memory Usage: 20 MB ```

.next JSON files

generated .next JSON files .next/required-server-files.json ``` {"version":1,"config":{"env":{},"eslint":{"ignoreDuringBuilds":false},"typescript":{"ignoreBuildErrors":false,"tsconfigPath":"tsconfig.json"},"distDir":".next","cleanDistDir":true,"assetPrefix":"","configOrigin":"next.config.js","useFileSystemPublicRoutes":true,"generateEtags":true,"pageExtensions":["tsx","ts","jsx","js"],"poweredByHeader":true,"compress":true,"analyticsId":"","images":{"deviceSizes":[640,750,828,1080,1200,1920,2048,3840],"imageSizes":[16,32,48,64,96,128,256,384],"path":"/_next/image","loader":"default","loaderFile":"","domains":[],"disableStaticImages":false,"minimumCacheTTL":60,"formats":["image/webp"],"dangerouslyAllowSVG":false,"contentSecurityPolicy":"script-src 'none'; frame-src 'none'; sandbox;","contentDispositionType":"inline","remotePatterns":[],"unoptimized":false},"devIndicators":{"buildActivity":true,"buildActivityPosition":"bottom-right"},"onDemandEntries":{"maxInactiveAge":60000,"pagesBufferLength":5},"amp":{"canonicalBase":""},"basePath":"","sassOptions":{},"trailingSlash":false,"i18n":null,"productionBrowserSourceMaps":false,"optimizeFonts":true,"excludeDefaultMomentLocales":true,"serverRuntimeConfig":{},"publicRuntimeConfig":{},"reactProductionProfiling":false,"reactStrictMode":null,"httpAgentOptions":{"keepAlive":true},"outputFileTracing":true,"staticPageGenerationTimeout":60,"swcMinify":true,"modularizeImports":{"@mui/icons-material":{"transform":"@mui/icons-material/{{member}}"},"date-fns":{"transform":"date-fns/{{member}}"},"lodash":{"transform":"lodash/{{member}}"},"lodash-es":{"transform":"lodash-es/{{member}}"},"ramda":{"transform":"ramda/es/{{member}}"},"react-bootstrap":{"transform":{"useAccordionButton":"modularize-import-loader?name=useAccordionButton&from=named&as=default!react-bootstrap/AccordionButton","*":"react-bootstrap/{{member}}"}},"antd":{"transform":"antd/lib/{{kebabCase member}}"},"ahooks":{"transform":{"createUpdateEffect":"modularize-import-loader?name=createUpdateEffect&from=named&as=default!ahooks/es/createUpdateEffect","*":"ahooks/es/{{member}}"}},"@ant-design/icons":{"transform":{"IconProvider":"modularize-import-loader?name=IconProvider&from=named&as=default!@ant-design/icons","createFromIconfontCN":"@ant-design/icons/es/components/IconFont","getTwoToneColor":"modularize-import-loader?name=getTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","setTwoToneColor":"modularize-import-loader?name=setTwoToneColor&from=named&as=default!@ant-design/icons/es/components/twoTonePrimaryColor","*":"@ant-design/icons/lib/icons/{{member}}"}},"next/server":{"transform":"next/dist/server/web/exports/{{ kebabCase member }}"}},"experimental":{"serverMinification":true,"serverSourceMaps":false,"caseSensitiveRoutes":false,"useDeploymentId":false,"useDeploymentIdServerActions":false,"clientRouterFilter":true,"clientRouterFilterRedirects":false,"fetchCacheKeyPrefix":"","middlewarePrefetch":"flexible","optimisticClientCache":true,"manualClientBasePath":false,"cpus":15,"memoryBasedWorkersCount":false,"isrFlushToDisk":true,"workerThreads":false,"optimizeCss":false,"nextScriptWorkers":false,"scrollRestoration":false,"externalDir":false,"disableOptimizedLoading":false,"gzipSize":true,"craCompat":false,"esmExternals":true,"isrMemoryCacheSize":52428800,"fullySpecified":false,"outputFileTracingRoot":"D:\\Workspace\\Code\\Hegg\\test-pages","swcTraceProfiling":false,"forceSwcTransforms":false,"largePageDataBytes":128000,"adjustFontFallbacks":false,"adjustFontFallbacksWithSizeAdjust":false,"typedRoutes":false,"instrumentationHook":false,"bundlePagesExternals":false,"optimizePackageImports":["lucide-react","@headlessui/react","@headlessui-float/react","@heroicons/react/20/solid","@heroicons/react/24/solid","@heroicons/react/24/outline","@visx/visx","@tremor/react","rxjs","@mui/material","recharts","@material-ui/core","react-use","@material-ui/icons","@tabler/icons-react","mui-core","react-icons/ai","react-icons/bi","react-icons/bs","react-icons/cg","react-icons/ci","react-icons/di","react-icons/fa","react-icons/fa6","react-icons/fc","react-icons/fi","react-icons/gi","react-icons/go","react-icons/gr","react-icons/hi","react-icons/hi2","react-icons/im","react-icons/io","react-icons/io5","react-icons/lia","react-icons/lib","react-icons/lu","react-icons/md","react-icons/pi","react-icons/ri","react-icons/rx","react-icons/si","react-icons/sl","react-icons/tb","react-icons/tfi","react-icons/ti","react-icons/vsc","react-icons/wi"],"trustHostHeader":false,"isExperimentalCompile":true},"configFileName":"next.config.js"},"appDir":"D:\\Workspace\\Code\\Hegg\\test-pages","relativeAppDir":"","files":[".next\\routes-manifest.json",".next\\server\\pages-manifest.json",".next\\build-manifest.json",".next\\prerender-manifest.json",".next\\prerender-manifest.js",".next\\server\\middleware-manifest.json",".next\\server\\middleware-build-manifest.js",".next\\server\\middleware-react-loadable-manifest.js",".next\\server\\app-paths-manifest.json",".next\\app-path-routes-manifest.json",".next\\app-build-manifest.json",".next\\server\\server-reference-manifest.js",".next\\server\\server-reference-manifest.json",".next\\react-loadable-manifest.json",".next\\server\\font-manifest.json",".next\\BUILD_ID",".next\\server\\next-font-manifest.js",".next\\server\\next-font-manifest.json"],"ignore":["node_modules\\next\\dist\\compiled\\@ampproject\\toolbox-optimizer\\**\\*"]} ``` .next/routes-manifest.json ``` {"version":3,"pages404":true,"caseSensitive":false,"basePath":"","redirects":[{"source":"/:path+/","destination":"/:path+","internal":true,"statusCode":308,"regex":"^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$"}],"headers":[],"dynamicRoutes":[{"page":"/[...page]","regex":"^/(.+?)(?:/)?$","routeKeys":{"nxtPpage":"nxtPpage"},"namedRegex":"^/(?.+?)(?:/)?$"}],"staticRoutes":[{"page":"/","regex":"^/(?:/)?$","routeKeys":{},"namedRegex":"^/(?:/)?$"},{"page":"/_not-found","regex":"^/_not\\-found(?:/)?$","routeKeys":{},"namedRegex":"^/_not\\-found(?:/)?$"},{"page":"/favicon.ico","regex":"^/favicon\\.ico(?:/)?$","routeKeys":{},"namedRegex":"^/favicon\\.ico(?:/)?$"},{"page":"/test","regex":"^/test(?:/)?$","routeKeys":{},"namedRegex":"^/test(?:/)?$"}],"dataRoutes":[],"rsc":{"header":"RSC","varyHeader":"RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url","prefetchHeader":"Next-Router-Prefetch","contentTypeHeader":"text/x-component"},"rewrites":[]} ``` .next/prerender-manifest.json ``` {"version":4,"routes":{"/favicon.ico":{"initialHeaders":{"cache-control":"public, max-age=0, must-revalidate","content-type":"image/x-icon","x-next-cache-tags":"_N_T_/layout,_N_T_/favicon.ico/layout,_N_T_/favicon.ico/route,_N_T_/favicon.ico"},"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/favicon.ico","dataRoute":null},"/test":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/test","dataRoute":"/test.rsc"},"/":{"experimentalBypassFor":[{"type":"header","key":"Next-Action"},{"type":"header","key":"content-type","value":"multipart/form-data"}],"initialRevalidateSeconds":false,"srcRoute":"/","dataRoute":"/index.rsc"}},"dynamicRoutes":{},"notFoundRoutes":[],"preview":{"previewModeId":"4142f2b5d13a2ade5ab33480fd19a314","previewModeSigningKey":"52a3c4280be070766a6030bcf996e1dfac2ed149b1ceb886fe1addcf6ad04b08","previewModeEncryptionKey":"d9fb92ba29ba9a3f3694b0c8193f5f1f9bfad72ed45a4aa40027c654cd291e0d"}} ```
MarcL commented 11 months ago

Hey @skordesign. We should have fixed this issue with #2313. It will be officially released onto the Netlify platform next week but you can install @netlify/plugin-nextjs@rc or @netlify/plugin-nextjs@4.40.3-rc.0 if you want to test it before.

Let us know if it doesn't fix your issue. Thanks.

skordesign commented 11 months ago

I've installed @netlify/plugin-nextjs@4.40.3-rc.0 and I get a Internal Server Error

ERROR  Error: Cannot find module 'next/dist\client\components\static-generation-async-storage.external.js'
Require stack:
- /var/task/.next/server/app/[...page]/page.js
- /var/task/node_modules/next/dist/server/require.js
- /var/task/node_modules/next/dist/server/next-server.js
- /var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js
- /var/task/___netlify-handler.js
- /var/runtime/index.mjs
    at Module._resolveFilename (node:internal/modules/cjs/loader:1077:15)
    at /var/task/node_modules/next/dist/server/require-hook.js:54:36
    at Module._load (node:internal/modules/cjs/loader:922:27)
    at Module.require (node:internal/modules/cjs/loader:1143:19)
    at mod.require (/var/task/node_modules/next/dist/server/require-hook.js:64:28)
    at require (node:internal/modules/cjs/helpers:121:18)
    at 25319 (/var/task/.next/server/app/[...page]/page.js:1:617)
    at __webpack_require__ (/var/task/.next/server/webpack-runtime.js:1:146)
    at 71775 (/var/task/.next/server/chunks/683.js:1:79793)
    at __webpack_require__ (/var/task/.next/server/webpack-runtime.js:1:146) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/var/task/.next/server/app/[...page]/page.js',
    '/var/task/node_modules/next/dist/server/require.js',
    '/var/task/node_modules/next/dist/server/next-server.js',
    '/var/task/.netlify/functions-internal/___netlify-handler/___netlify-handler.js',
    '/var/task/___netlify-handler.js',
    '/var/runtime/index.mjs'
  ]
}
skordesign commented 11 months ago

Hi, the error I mentioned above only happens when I build and deploy on my local machine (Windows 11). After I switched to Github Action using Linux, it worked fine.

OOCAZ commented 11 months ago

Thanks for the fix! Was having the same issue but not locally, only on Netlify deployment, I saw this issue and it instantly fixed it. Thank you, thank you, thank you so much! It was driving me crazy trying to figure out what was going on. But thanks to your hard work @MarcL and everyone else who helped I got a food pantries service back online. Amazing work, thanks so much!

Andre-Diamond commented 11 months ago

I got this error when trying to access my new live API route. Installing @netlify/plugin-nextjs@rc fixed it.

szamanr commented 10 months ago

i upgraded to 4.41.2 but it didn't fix the issue. now i get an internal server error. happens only on netlify, not locally.

maslomeister commented 9 months ago

Having same problem with

"next": "^14.0.4" "@netlify/plugin-nextjs": "^4.41.3"

pnpm run build && pnpm run start works fine

netlfiy deploy --build --prod builds fine, but upon visiting the website it shows Cannot find module 'styled-jsx/package.json'