opennextjs / opennextjs-netlify

Open Next.js adapter for Netlify
https://opennext.js.org/netlify
676 stars 86 forks source link

[Bug]: Using deploy preview from CLI results in assets not being found #1725

Closed petervmeijgaard closed 2 years ago

petervmeijgaard commented 2 years ago

Summary

When using the CLI to build and deploy a new deploy preview, the assets that are loaded on the page result in a 404 Not Found due to the fact that the files located in the _next/static directory are now located in the static-directory. The references on the page are still pointing to the _next/static/* directory.

You can view this here: https://setup-netlify--next-anwb-sandbox.netlify.app/

You'll notice that the deploy preview isn't loading any CSS/JS and when inspecting the network tab, you'll see a lot of 404 - Not Found errors. When visiting one of the CSS files in the browser, you'll see the default Page Not Found screen from Netlify: https://setup-netlify--next-anwb-sandbox.netlify.app/_next/static/css/ab44ce7add5c3d11.css

However, if you remove the _next, the assets can be found: https://setup-netlify--next-anwb-sandbox.netlify.app/static/css/ab44ce7add5c3d11.css

I think this has something to do with the redirects that are added here: https://github.com/netlify/next-runtime/blob/main/packages/runtime/src/helpers/redirects.ts#L77

However, this seems to work correctly with a production deploy as both the _next/static and static directories are present: https://next-anwb-sandbox.netlify.app/static/css/ab44ce7add5c3d11.css https://next-anwb-sandbox.netlify.app/_next/static/css/ab44ce7add5c3d11.css

Steps to reproduce

  1. Initialize a new Next application and add the Netlify CLI with the Netlify Next plugin
  2. Run netlify deploy --prod --build
  3. Wait for the deploy to finish and see that prod has been deployed correctly
  4. Run netlify build --context deploy-preview
  5. Run netlify deploy --alias=my-custom-alias
  6. Wait for the deploy to finish and see that the assets are loaded incorrectly

A link to a reproduction repository

No response

Next Runtime version

4.28.2

More information about your build

What OS are you using?

Linux

Your netlify.toml file

`netlify.toml` ```toml # example netlify.toml [build] command = "next build" functions = "netlify/functions" publish = ".next" [[plugins]] package = "@netlify/plugin-nextjs" ```

Your public/_redirects file

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

Your next.config.js file

`next.config.js` ```js /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, } module.exports = nextConfig ```

Builds logs (or link to your logs)

Build logs ``` ──────────────────────────────────────────────────────────────── Netlify Build ──────────────────────────────────────────────────────────────── ❯ Version @netlify/build 28.0.1 ❯ Flags dry: false offline: false ❯ Current directory [REDACTED]/next-sandbox ❯ Config file [REDACTED]/next-sandbox/netlify.toml ❯ Context production ❯ Using Next.js Runtime - v4.28.2 ──────────────────────────────────────────────────────────────── 1. @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 689ms) ──────────────────────────────────────────────────────────────── 2. build.command from netlify.toml ──────────────────────────────────────────────────────────────── $ next build info - Linting and checking validity of types info - Creating an optimized production build info - Compiled successfully info - Collecting page data info - Generating static pages (3/3) info - Finalizing page optimization Route (pages) Size First Load JS ┌ ○ / 4.23 kB 76.4 kB ├ └ css/ae0e3e027412e072.css 707 B ├ /_app 0 B 72.1 kB ├ ○ /404 181 B 72.3 kB └ λ /api/hello 0 B 72.1 kB + First Load JS shared by all 72.4 kB ├ chunks/framework-8c5acb0054140387.js 45.4 kB ├ chunks/main-d2a793b6dc23a82a.js 25.7 kB ├ chunks/pages/_app-fdaca63b9de4692d.js 295 B ├ chunks/webpack-8fa1640cc84ba8fe.js 750 B └ css/ab44ce7add5c3d11.css 247 B λ (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps) ○ (Static) automatically rendered as static HTML (uses no initial props) (build.command completed in 2.9s) ──────────────────────────────────────────────────────────────── 3. @netlify/plugin-nextjs (onBuild event) ──────────────────────────────────────────────────────────────── { functionsDir: '[REDACTED]/next-sandbox/.netlify/functions-internal' } Patching [REDACTED]/next-sandbox/node_modules/next/dist/server/base-server.js Done Patching [REDACTED]/next-sandbox/node_modules/next/dist/server/next-server.js Done Moving static page files to serve from CDN... Moved 1 files Using Netlify Edge Functions for image format detection. Set env var "NEXT_DISABLE_EDGE_IMAGES=true" to disable. 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/hello', to: '/.netlify/functions/_api_hello-handler', status: 200 }, { from: '/api/*', to: '/.netlify/functions/___netlify-handler', status: 200 }, { from: '/favicon.ico', to: '/favicon.ico', 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/qAe-kNoPc36MLpwoilfec/index.json', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/', to: '/.netlify/functions/___netlify-handler', status: 200, force: false }, { from: '/*', to: '/.netlify/functions/___netlify-handler', status: 200 } ]. (@netlify/plugin-nextjs onBuild completed in 783ms) ──────────────────────────────────────────────────────────────── 4. Functions bundling ──────────────────────────────────────────────────────────────── The Netlify Functions setting targets a non-existing directory: netlify/functions Packaging Functions from .netlify/functions-internal directory: - ___netlify-handler/___netlify-handler.js - ___netlify-odb-handler/___netlify-odb-handler.js - _api_hello-handler/_api_hello-handler.js - _ipx/_ipx.js (Functions bundling completed in 9.9s) ──────────────────────────────────────────────────────────────── 5. Edge Functions bundling ──────────────────────────────────────────────────────────────── Packaging Edge Functions from .netlify/edge-functions directory: - ipx (Edge Functions bundling completed in 2.5s) ──────────────────────────────────────────────────────────────── 6. @netlify/plugin-nextjs (onPostBuild event) ──────────────────────────────────────────────────────────────── Next.js cache saved. (@netlify/plugin-nextjs onPostBuild completed in 37ms) ──────────────────────────────────────────────────────────────── Netlify Build Complete ──────────────────────────────────────────────────────────────── ```

Function logs

Function logs ``` # Paste logs here ```

.next JSON files

.next/required-server-files.json ```json { "version": 1, "config": { "env": {}, "webpack": null, "webpackDevMiddleware": null, "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" ], "target": "server", "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;", "remotePatterns": [], "unoptimized": false }, "devIndicators": { "buildActivity": true, "buildActivityPosition": "bottom-right" }, "onDemandEntries": { "maxInactiveAge": 15000, "pagesBufferLength": 2 }, "amp": { "canonicalBase": "" }, "basePath": "", "sassOptions": {}, "trailingSlash": false, "i18n": null, "productionBrowserSourceMaps": false, "optimizeFonts": true, "excludeDefaultMomentLocales": true, "serverRuntimeConfig": {}, "publicRuntimeConfig": {}, "reactStrictMode": true, "httpAgentOptions": { "keepAlive": true }, "outputFileTracing": true, "staticPageGenerationTimeout": 60, "swcMinify": true, "experimental": { "optimisticClientCache": true, "manualClientBasePath": false, "legacyBrowsers": false, "newNextLinkBehavior": true, "cpus": 23, "sharedPool": true, "profiling": false, "isrFlushToDisk": true, "workerThreads": false, "pageEnv": false, "optimizeCss": false, "nextScriptWorkers": false, "scrollRestoration": false, "externalDir": false, "disableOptimizedLoading": false, "gzipSize": true, "swcFileReading": true, "craCompat": false, "esmExternals": true, "appDir": false, "isrMemoryCacheSize": 52428800, "fullySpecified": false, "outputFileTracingRoot": "", "swcTraceProfiling": false, "forceSwcTransforms": false, "largePageDataBytes": 128000, "enableUndici": false, "adjustFontFallbacks": false, "adjustFontFallbacksWithSizeAdjust": false, "trustHostHeader": false }, "configFileName": "next.config.js" }, "appDir": "[REDACTED]/next-sandbox", "files": [ ".next/routes-manifest.json", ".next/server/pages-manifest.json", ".next/build-manifest.json", ".next/prerender-manifest.json", ".next/server/middleware-manifest.json", ".next/react-loadable-manifest.json", ".next/server/font-manifest.json", ".next/BUILD_ID" ], "ignore": [ "node_modules/next/dist/compiled/@ampproject/toolbox-optimizer/**/*" ] } ```
.next/routes-manifest.json ```json { "version": 3, "pages404": true, "basePath": "", "redirects": [ { "source": "/:path+/", "destination": "/:path+", "internal": true, "statusCode": 308, "regex": "^(?:/((?:[^/]+?)(?:/(?:[^/]+?))*))/$" } ], "headers": [], "dynamicRoutes": [], "staticRoutes": [ { "page": "/", "regex": "^/(?:/)?$", "routeKeys": {}, "namedRegex": "^/(?:/)?$" } ], "dataRoutes": [], "rewrites": [] } ```
.next/prerender-manifest.json ```json { "version": 3, "routes": {}, "dynamicRoutes": {}, "preview": { "previewModeId": "d9aad6b54a521ddbc0986b2de60b85cf", "previewModeSigningKey": "dd23cf4a1c40fe5906eeb83ba4077ac002be5d535714301995d7754b3c0eeb57", "previewModeEncryptionKey": "aa183de1e4c0a731fe9801db2b10421924e49989a0b7b2433f5f32ed18973881" }, "notFoundRoutes": [] } ```
ascorbic commented 2 years ago

Hi. You need to always deploy using netlify deploy --build, otherwise the generated rewrites are not included in the deploy. More details here

petervmeijgaard commented 2 years ago

Thank you! As you can see, this fixed my problem!