Closed Rafcin closed 1 year ago
Hi @Rafcin ππ½, thank you for raising this issue. What AWS region are you trying to deploy your app in?
I'm deploying it in US West 2, it's an SSR next JS app and it's built with NX as a monorepo so versus a standard monorepo it uses a single package.json and a single node modules folder.
I also opened a support ticket with AWS and they recommended setting it from web dynamic to web although that doesn't work because if I switch it to web I think that means it assumes it's just a statically generated site which is not what I want. Also switching to web builds correctly but it doesn't create a cloud front distribution and it doesn't generate a rewrite either because it doesn't have the confront distribution and so when it deploys it's just a 404.
I've also spoken to a lot of people that have tried this and nobody's been able to get it to build, at least all the people that have opened issues. I also spoke with Josef for a few days and he's been extremely helpful (thank you Josef) and we originally looked at a different error which was it couldn't find next JS to build but I was essentially going into the apps folder and running yarn build but I stopped using that because it didn't make sense, if I just install NX and then run NX build project name it builds it correctly without any issues. So manually building each app doesn't make sense, I added a package Jason when I originally deployed it to trick it into thinking it's a next JS SSR app so I don't need to change it later on, I think it's just a matter of pointing the build to the correct place or modifying the build settings but at this point I'm not sure I'm really lost.
If you have any more questions or if you want to see the repo just let me know send me an email of food to add to it, and if you need anything else I have this page constantly open I'll be here as long as it takes ππ
I opened a support ticket with AWS, and at this point, I'm being redirected here. If it helps the following things have been tried (recommended by support)
After descending into madness for a bit I've gotten somewhere new now. I encountered this once when trying different methods to build and I'm pretty sure this happens only if build is run from the app root via next build
. Building outside the app with NX works fine on the other hand.
It throws invalid hook errors and the only thing the pages share in common in terms of hooks is Redux. But again building with NX works fine and building the app with next build in app/news shits the bed.
Amplify.yml
- frontend:
phases:
preBuild:
commands:
- cd ../..
- nvm install v16.2.0
- echo "//registry.npmjs.org/:_authToken={TOKEN}" > .npmrc
# Replicates NPM CI with RM and Frozen Lock
- rm -rf node_modules **/node_modules
- rm -rf yarn.lock **/yarn.lock
- yarn cache clean
- yarn install --frozen-lockfile
- rm -r node_modules/@next/swc-linux-x64-gnu
- ls
build:
commands:
- ls
- npx nx build news
- cp -r node_modules apps/news/node_modules
- cd apps/news
- ls
- cp -r dist/.next .next
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
appRoot: apps/news
Hi @Rafcin sorry for the delay and thank you for all of this context. Just out of curiosity, are you able to successfully build your app locally? Also, can you provide the App ID and region your app is deployed again?
Also it would be helpful if you could provide a sample repo with a similar structure. I was able to get my basic NX/Next.js app to deploy correctly with similar build commands.
The app ID it deployed with is d1qgwpip26q5k8
It builds correctly if you use NX build but you have to run NX build in the root of the repo. If you run NX build appname in the apps folder it fails. Same thing if you run yarn build in the apps folder.
The error it's throwing now is one of the pages post[id], 500 and 404 have invalid hook calls. It's odd.
It would be a lot of work to reproduce the repo, instead I'll add you to the git repo and I'll give you admin access as well.
@hloriana invite sent
From what I've been able to put together at this point, if Amplify didn't need to run the build step inside the root it would work fine.
If you set the root as apps/appname and you have the package json inside the app then it will automatically decide it needs to run next build. However if you don't have the json then you can't detect the app as Next SSR.
The other problem is if you remove the json and already have it set as Next SSR and point the artifact to dist then it will build but the artifact size for some reason is only 7mb and when it gets to the deploy stage it blows up with that error code 7.
Then if you get error code 7 and switch it to Web_Dynamic to Web and redeploy it works BUT it doesn't create and assets or a CloudFront distribution and the resulting amplify url is just a 404.
So that leads me to believe that the node modules and build have to occur in the apps folder anyway to make the build process work.
Hi @Rafcin so after further investigation with the team, hosting Next.js apps within an NX monorepo is not fully supported yet but we are rolling out an update that should fix this issue.
Some customers are able to workaround this by using this amplify.yml
version: 1
applications:
- frontend:
phases:
build:
commands:
# This step will build app with Nx framework
- cd ../../
- npm install
- npx nx run my-app:build
# This step will build/update SSR resources(S3, Cloudfront, Lambda@Edge)
- cd apps/my-app
- npm install
artifacts:
baseDirectory: ../../dist/apps/my-app/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
appRoot: apps/my-app
@hloriana Thanks for the update.
Is there a timeline for when this will be released? I will need to release updates to my site at some point in the next week.
Like I mentioned in other issues, the solution you provided below won't work. I've tried this and that's why I opened the issue in the first place. The dist location doesn't matter, but if you run Yarn install (in my case instead of NPM) it will blow up on install and it will attempt to run next build
immediately after yarn install
@hloriana This solution was mentioned by Victor here https://github.com/aws-amplify/amplify-console/issues/1866
In theory it should work but if you run npm or yarn install it will trigger next build
and next build will blow up because it can't find node_modules/.bin/next.
I can't stop the amplify build process from running next build it just does that on it's own
@Rafcin I do not have an exact date but I will be sure to keep you updated.
Adding some extra info. The following YML allows it to partially build. However it blows up on npx severless
- frontend:
phases:
preBuild:
commands:
- cd ../..
- nvm install v16.2.0
- echo "//registry.npmjs.org/:_authToken={TOKEN}" > .npmrc
# Replicates NPM CI with RM and Frozen Lock
- rm -rf node_modules **/node_modules
- rm -rf yarn.lock **/yarn.lock
- yarn cache clean
- yarn install --frozen-lockfile
- npx nx run news:build
- ls
build:
commands:
- ls
# - npx nx build news
# - cp -r node_modules apps/news/node_modules
- cd apps/news
- yarn install --frozen-lockfile
# - cp dist/package.json package.json
# - rm -rf node_modules **/node_modules
# - rm -rf yarn.lock **/yarn.lock
# - yarn cache clean
# - yarn install --frozen-lockfile
# - rm -r node_modules/@next/swc-linux-x64-gnu
# - ls
# - cp -r dist/.next .next
artifacts:
baseDirectory: dist/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
appRoot: apps/news
2021-11-19T20:07:54.837Z [INFO]: Starting SSR Build...
2021-11-19T20:09:15.486Z [ERROR]: News {
status: 'loading',
isLoading: true,
isSuccess: false,
isError: false,
isIdle: false,
data: undefined,
dataUpdatedAt: 0,
error: null,
errorUpdatedAt: 0,
failureCount: 0,
isFetched: false,
isFetchedAfterMount: false,
isFetching: true,
isRefetching: false,
isLoadingError: false,
isPlaceholderData: false,
isPreviousData: false,
isRefetchError: false,
isStale: true,
refetch: [Function: bound refetch],
remove: [Function: bound remove]
}
Terminating logging...
Kgnanask from the Amplify discord is looking into why it terminated. At the moment the reason for it terminating is unknown, the logs didn't say why.
@swaminator So regarding how the app is built with NX, will it be possible at all for me to deploy my app?
@ferdingler @swaminator Hello again! Just wanted to check-in and ask, has a solution been found to the nx deployment issue? I really need to know if I need to move away from NX or not because I've got some higher-up people breathing down my neck ;-; and I need to deploy something soon or rework my project to not use NX. π
I noticed when the artifacts are zipped, it seems that it only zips 7 mb although it should be 90 something MB.
2021-12-01T09:08:31.363Z [INFO]: No custom headers found.
2021-12-01T09:08:31.487Z [INFO]: # Starting build artifact upload process...
2021-12-01T09:08:32.307Z [INFO]: # Build artifact is: 7MB
2021-12-01T09:08:32.307Z [INFO]: # Uploading build artifact '__artifacts.zip'...
2021-12-01T09:08:32.323Z [INFO]: # Build artifact is: 7MB
2021-12-01T09:08:32.324Z [INFO]: # Uploading build artifact '__artifactsHash.zip'...
2021-12-01T09:08:32.635Z [INFO]: # Build artifact upload completed
2021-12-01T09:08:32.636Z [INFO]: # Starting environment caching...
2021-12-01T09:08:32.636Z [INFO]: # Uploading environment cache artifact...
2021-12-01T09:08:32.728Z [INFO]: # Environment caching completed
Terminating logging...
I also modified the serverless yml to add the desired cloudfront headers. Don't know if it will work.
d3mtx39i8kz2p9:
component: '@sls-next/serverless-component@1.18.0'
inputs:
build:
cmd: ':'
cleanupDotNext: false
timeout:
defaultLambda: 30
apiLambda: 30
imageLambda: 30
regenerationLambda: 30
cloudfront:
defaults:
forward:
headers:
- CloudFront-Is-Desktop-Viewer
- CloudFront-Is-Mobile-Viewer
- CloudFront-Is-Tablet-Viewer
- CloudFront-Viewer-Country
- CloudFront-Viewer-Latitude
- CloudFront-Viewer-Longitude
- CloudFront-Viewer-Time-Zone
- CloudFront-Viewer-City
- Authorization
build:
env:
AMPLIFY_DIFF_DEPLOY: 'false'
AMPLIFY_MONOREPO_APP_ROOT: apps/news
I was speaking with another user Juan who was able to build a NX repo based on https://github.com/bmvantunes/aws-amplify-deploy-test-nx
When I used this method I had a similar issue where the project complains there's no SSR resource file and the artifact zip is also only 7mb. I think it's just about the artifact being wrong although that I can't debug and I have no idea why it's not packing the entire artifact normally.
same issue here :(
Seeing this error with yarn workspaces and was hoping to find some useful information here or a potential solution. Seems like a big oversight considering many builds with next are using monorepos at this point. Any help would be much appreciated.
Seeing this error with yarn workspaces and was hoping to find some useful information here or a potential solution. Seems like a big oversight considering many builds with next are using monorepos at this point. Any help would be much appreciated.
If I remember correctly you need to spin up a new project so the amplify system can detect it's a monorepo setup, when setting up you'll be given the option to specify your target as apps/appname or however your structure looks and that should work then.
Hi forks, i got a good news, after many hours of tried and error, my Nextjs app able to deploy on Amplify without fail, i can visit the site, and SSR rendering same doing fine, but all nextjs API handles return 503 error "Cannot find module '../../../webpack-api-runtime.js"...., still figuring out what is it.
here is my amplify.yml:
version: 1
applications:
- appRoot: apps/nextjsapp
backend:
phases:
build:
commands:
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
# This step will build app with Nx framework
- cd ../../
- nvm install
- nvm use
- yarn install --frozen-lockfile
build:
commands:
- yarn nx build nextjsapp --prod
- cd apps/nextjsapp
- ln -s ../../dist/apps/nextjsapp/.next .next
- ln -s ../../node_modules node_modules
- export AMPLIFY_SSR_BUILD=true
artifacts:
baseDirectory: ../../dist/apps/nextjsapp/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Override the serverless yml by switching to the. SLS package to version
βcomponentβ: ***@***.******@***.***β'
This should solve the problem with the 503 on API routes with the latest
version of Next. (Should be fine with next 11 as well)
On Sun, Apr 3, 2022, 7:02 AM Joseph cheng @.***> wrote:
Hi forks, i got a good news, after many hours of tried and error, my Nextjs app able to deploy on Amplify without fail, i can visit the site, and SSR rendering same doing fine, but all nextjs API handles return 503 error "Cannot find module '../../../webpack-api-runtime.js"...., still figuring out what is it.
here is my amplify.yml:
version: 1applications:
- appRoot: apps/nextjsapp backend: phases: build: commands:
- amplifyPush --simple frontend: phases: preBuild: commands:
This step will build app with Nx framework
- cd ../../
- nvm install
- nvm use
- yarn install --frozen-lockfile build: commands:
- yarn nx build nextjsapp --prod
- cd apps/nextjsapp
- ln -s ../../dist/apps/nextjsapp/.next .next
- ln -s ../../node_modules node_modules
- export AMPLIFY_SSR_BUILD=true artifacts: baseDirectory: ../../dist/apps/nextjsapp/.next files:
- '*/' cache: paths:
- node_modules/*/
β Reply to this email directly, view it on GitHub https://github.com/aws-amplify/amplify-hosting/issues/2377#issuecomment-1086875838, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACQCG6YO4CF7VJ7672S2X23VDGQHTANCNFSM5H3QVSQA . You are receiving this because you were mentioned.Message ID: @.***>
Hi Rafcin, the sls component version seems got redacted
'@sls-next/serverless-component@3.7.0-alpha.11'
When you build, using the amplify YML after prebuild run - cp config/serverless.yml serverless.yml
and just overwrite the generated sls file.
ID:
component: '@sls-next/serverless-component@3.7.0-alpha.11'
inputs:
memory:
defaultLambda: 1024
apiLambda: 2048
imageLambda: 2048
timeout:
defaultLambda: 30
apiLambda: 30
imageLambda: 30
regenerationLambda: 30
cloudfront:
defaults:
forward:
headers:
- CloudFront-Is-Desktop-Viewer
- CloudFront-Is-Mobile-Viewer
- CloudFront-Is-Tablet-Viewer
- CloudFront-Viewer-Country
- CloudFront-Viewer-Latitude
- CloudFront-Viewer-Longitude
- CloudFront-Viewer-Time-Zone
- CloudFront-Viewer-City
- Authorization
build:
env:
AMPLIFY_DIFF_DEPLOY: 'false'
AMPLIFY_MONOREPO_APP_ROOT: apps/fox
Thanks @Rafcin after updated the sls component version, the API backed is working great, but the frontend is return 503 error, and the log show SQS permission error, and then i attached SQS policy into the lambda role, the frontend working immediately. but some pages works, but pages still getting Minified React error #321
errors..., i think i should switch back to yarn workspace.....
Oh right you are using NX. As of now Amplify and NX don't really work together. I suggest trying Turborepo, you will def find it better. It's just as fast and it takes 2 seconds to set up with workspaces.
[image: created with MySignature.io] https://mysignature.io/?utm_source=logo Raf Szuminski
Developer | TacoTuesdays.com P: (949)-338-7506 E: @.*** https://mysignature.io/editor/?utm_source=freepixel IMPORTANT: The contents of this email and any attachments are confidential. It is strictly forbidden to share any part of this message with any third party, without a written consent of the sender. If you received this message by mistake, please reply to this message and follow with its deletion, so that we can ensure such a mistake does not occur in the future.
On Mon, Apr 4, 2022 at 12:55 AM Joseph cheng @.***> wrote:
Thanks @Rafcin https://github.com/Rafcin after updated the sls component version, the API backed is working great, but the frontend is return 503 error, and the log show SQS permission error, and then i attached SQS policy into the lambda role, the frontend working immediately. but some pages works, but pages still getting Minified React error #321 errors..., i think i should switch back to yarn workspace.....
β Reply to this email directly, view it on GitHub https://github.com/aws-amplify/amplify-hosting/issues/2377#issuecomment-1087231623, or unsubscribe https://github.com/notifications/unsubscribe-auth/ACQCG6ZSPS2RA7HLRJVZHSDVDKN6VANCNFSM5H3QVSQA . You are receiving this because you were mentioned.Message ID: @.***>
Just figure out the React error actually came from React v18 issue, after downgrade to v17 my app working well without any problem, my workaround is:
version: 1
applications:
- appRoot: apps/nextjsapp
backend:
phases:
build:
commands:
- amplifyPush --simple
frontend:
phases:
preBuild:
commands:
# This step will build app with Nx framework
- cd ../../
- nvm install
- nvm use
- yarn install --frozen-lockfile
build:
commands:
- yarn nx build nextjsapp --prod
- cd apps/nextjsapp
# create symbolic link from root to app folder
- ln -s ../../dist/apps/nextjsapp/.next .next
- ln -s ../../node_modules node_modules
# enable SSR build flag to transpile libs/ui
- export AMPLIFY_SSR_BUILD=true
artifacts:
baseDirectory: ../../dist/apps/nextjsapp/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
next.config.js
const withNx = require('@nrwl/next/plugins/with-nx');
const path = require('path');
const isSSRBuild = process.env.AMPLIFY_SSR_BUILD === 'true';
/**
* @type {import('@nrwl/next/plugins/with-nx').WithNxOptions}
**/
const nextConfig = {
nx: {
// Set this to true if you would like to to use SVGR
// See: https://github.com/gregberge/svgr
svgr: false,
},
webpack (config, { defaultLoaders }) {
if (isSSRBuild) {
// XXX: This is a workaround for a bug in Amplify SSR deployment
config.module.rules.push({
test: /\.([jt])sx?$/,
include: [path.join(__dirname, '../../libs')],
exclude: /node_modules/,
use: [defaultLoaders.babel],
});
}
config.module.rules.push({
test: /\.svg$/,
use: [
{
loader: '@svgr/webpack',
options: {
svgoConfig: {
plugins: [
{
name: 'preset-default',
params: {
overrides: { removeViewBox: false },
},
},
],
},
},
},
],
});
return config;
},
};
module.exports = withNx(nextConfig);
indiejoseph. If I could buy you a beer I would.
Legend.
That's awesome @indiejoseph! Thanks for figuring this out π
Hi π , if there's anything from the Nx side that can make the build work better please let us know.
For example, in @indiejoseph 's solution, the AMPLIFY_SSR_BUILD
is set manually for Nx to check, but if this is provided by default we can build support into @nrwl/next
directly.
Generating with the @indiejoseph config I encounter this error
package.json
versions
"next": "13.0.0",
"react": "18.2.0",
"react-dom": "18.2.0",
2022-11-01T19:45:33.159Z [INFO]:
2022-11-01T19:45:33.160Z [INFO]: > nx run generic-portal:build:production
2022-11-01T19:45:34.768Z [INFO]: warn - No build cache found. Please configure build caching for faster rebuilds. Read more: https://nextjs.org/docs/messages/no-cache
2022-11-01T19:45:34.787Z [INFO]: Attention: Next.js now collects completely anonymous telemetry regarding usage.
2022-11-01T19:45:34.787Z [INFO]: This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry
2022-11-01T19:45:34.889Z [INFO]: info - Skipping linting
2022-11-01T19:45:34.891Z [INFO]: info - Checking validity of types...
2022-11-01T19:45:40.683Z [INFO]: info - Creating an optimized production build...
2022-11-01T19:45:53.767Z [INFO]: info - Compiled successfully
2022-11-01T19:45:53.768Z [INFO]: info - Collecting page data...
2022-11-01T19:45:55.356Z [INFO]: info - Generating static pages (0/5)
2022-11-01T19:45:55.448Z [INFO]: info - Generating static pages (1/5)
2022-11-01T19:45:55.452Z [INFO]: info - Generating static pages (2/5)
2022-11-01T19:45:55.461Z [INFO]: info - Generating static pages (3/5)
2022-11-01T19:45:56.217Z [INFO]: info - Generating static pages (5/5)
2022-11-01T19:45:56.230Z [INFO]: info - Finalizing page optimization...
2022-11-01T19:45:56.234Z [INFO]:
2022-11-01T19:45:56.250Z [INFO]: Route (pages) Size First Load JS
β β / 2.33 kB 367 kB
β /_app 0 B 87.9 kB
β β /[tenant] 313 B 88.2 kB
β β /[tenant]/[projectId] (858 ms) 278 kB 643 kB
β β /404 181 B 88.1 kB
β Ξ» /api/test 0 B 87.9 kB
+ First Load JS shared by all 91.6 kB
β chunks/framework-22108eb722d84e59.js 45.4 kB
β chunks/main-3feb51816554d004.js 25.7 kB
β chunks/pages/_app-223d5ef6ed9f53b3.js 15 kB
β chunks/webpack-15199bcd0330b034.js 1.8 kB
β css/50af800ef8042ad4.css 3.68 kB
2022-11-01T19:45:56.250Z [INFO]: Ξ» (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)
β (Static) automatically rendered as static HTML (uses no initial props)
2022-11-01T19:45:57.363Z [INFO]:
2022-11-01T19:45:57.364Z [INFO]:
> NX Successfully ran target build for project generic-portal
2022-11-01T19:45:57.375Z [INFO]: # Executing command: cd apps/generic-portal
2022-11-01T19:45:57.394Z [INFO]: # Executing command: ln -s ../../dist/apps/generic-portal/.next .next
2022-11-01T19:45:57.395Z [INFO]: # Executing command: ln -s ../../node_modules node_modules
2022-11-01T19:45:57.396Z [INFO]: # Executing command: export AMPLIFY_SSR_BUILD=true
2022-11-01T19:45:57.396Z [INFO]: Starting SSR Build...
2022-11-01T19:46:22.690Z [ERROR]: Serverless Error ----------------------------------------
Terminating logging...
we're successfully deploy nx
to amplify using this approach
// apps/web-app/next.config.js
module.exports = {
output: 'standalone',
experimental: {
// this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'),
},
}
distDir
on server.js
version: 1
applications:
- frontend:
phases:
preBuild:
commands:
- yarn install
build:
commands:
- npx nx run web-app:build:production
- mv ./dist/apps/web-app/.next/standalone/apps/web-app/* ./dist/apps/web-app/.next/standalone/
- sed -i 's/\/..\/..//' ./dist/apps/web-app/.next/standalone/server.js
artifacts:
baseDirectory: dist/apps/web-app/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
works like charms
we're successfully deploy
nx
to amplify using this approach
- using standalone build with monorepo configurations
// apps/web-app/next.config.js module.exports = { output: 'standalone', experimental: { // this includes files from the monorepo base two directories up outputFileTracingRoot: path.join(__dirname, '../../'), }, }
- on build steps, we move standalone builds from basedir to standalone directory, then replace relative path from
distDir
onserver.js
version: 1 applications: - frontend: phases: preBuild: commands: - yarn install build: commands: - npx nx run web-app:build:production - mv ./dist/apps/web-app/.next/standalone/apps/web-app/* ./dist/apps/web-app/.next/standalone/ - sed -i 's/\/..\/..//' ./dist/apps/web-app/.next/standalone/server.js artifacts: baseDirectory: dist/apps/web-app/.next files: - '**/*' cache: paths: - node_modules/**/*
works like charms
Does this work for SSR? I'm getting the following error on cloudfront from Monitoring menu `
Β | 2022-12-03T11:11:00.939-05:00 | node:internal/modules/cjs/loader:936 |
---|---|---|
Β | 2022-12-03T11:11:00.939-05:00 | throw err; |
Β | 2022-12-03T11:11:00.939-05:00 | ^ |
Β | 2022-12-03T11:11:00.939-05:00CopyError: Cannot find module '/var/task/server.js' | Error: Cannot find module '/var/task/server.js' |
`
Just figure out the React error actually came from React v18 issue, after downgrade to v17 my app working well without any problem, my workaround is:
version: 1 applications: - appRoot: apps/nextjsapp backend: phases: build: commands: - amplifyPush --simple frontend: phases: preBuild: commands: # This step will build app with Nx framework - cd ../../ - nvm install - nvm use - yarn install --frozen-lockfile build: commands: - yarn nx build nextjsapp --prod - cd apps/nextjsapp # create symbolic link from root to app folder - ln -s ../../dist/apps/nextjsapp/.next .next - ln -s ../../node_modules node_modules # enable SSR build flag to transpile libs/ui - export AMPLIFY_SSR_BUILD=true artifacts: baseDirectory: ../../dist/apps/nextjsapp/.next files: - '**/*' cache: paths: - node_modules/**/*
next.config.js
const withNx = require('@nrwl/next/plugins/with-nx'); const path = require('path'); const isSSRBuild = process.env.AMPLIFY_SSR_BUILD === 'true'; /** * @type {import('@nrwl/next/plugins/with-nx').WithNxOptions} **/ const nextConfig = { nx: { // Set this to true if you would like to to use SVGR // See: https://github.com/gregberge/svgr svgr: false, }, webpack (config, { defaultLoaders }) { if (isSSRBuild) { // XXX: This is a workaround for a bug in Amplify SSR deployment config.module.rules.push({ test: /\.([jt])sx?$/, include: [path.join(__dirname, '../../libs')], exclude: /node_modules/, use: [defaultLoaders.babel], }); } config.module.rules.push({ test: /\.svg$/, use: [ { loader: '@svgr/webpack', options: { svgoConfig: { plugins: [ { name: 'preset-default', params: { overrides: { removeViewBox: false }, }, }, ], }, }, }, ], }); return config; }, }; module.exports = withNx(nextConfig);
Thank you for this I was able to deploy with monorepo using this amplify config. Even though, from the announment of the Nextjs 12 and 13 support the deployment platform changed from Web Dynamic to Web Compute and everything started to fail again. The frontend compiles but when loading from web browser it generates a 500 error that is logged to cloudfront Monitoring as:
`
Β | 2022-12-03T11:11:00.939-05:00 | node:internal/modules/cjs/loader:936 |
---|---|---|
Β | 2022-12-03T11:11:00.939-05:00 | throw err; |
Β | 2022-12-03T11:11:00.939-05:00 | ^ |
Β | 2022-12-03T11:11:00.939-05:00CopyError: Cannot find module '/var/task/server.js' | Error: Cannot find module '/var/task/server.js' |
` This is using Nextjs SSR, so when trying to look for the server.js in my local machine build it isn't generated either, even though for a no monorepo set up it runs fine
@manxon did you find any solution for next.js 12 apps with monorepo and nx?
@hloriana Do you have any news on this issue?
There are two approaches to this issue:
amplify.yml
version: 1
applications:
- appRoot: apps/base
frontend:
phases:
preBuild:
commands:
# This step will build app with Nx framework
- cd ../../
- yarn install --frozen-lockfile
build:
commands:
- yarn nx build base --prod --skip-nx-cache
- mv ./dist/apps/base/.next/standalone/apps/base/* ./dist/apps/base/.next/standalone/
# - mv ./dist/apps/base/.next/standalone/* ./dist/apps/base/.next
- sed -i 's/\/..\/..//' ./dist/apps/base/.next/standalone/server.js
- cd apps/base
# create symbolic link from root to app folder
- ln -s ../../dist/apps/base/.next .next
- ln -s ../../node_modules node_modules
- ln -s ../../libs libs
artifacts:
baseDirectory: ../../dist/apps/base/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
next.config.js (Next js 12)
experimental: {
// this includes files from the monorepo base two directories up
outputFileTracingRoot: path.join(__dirname, '../../'),
},
@manxon Actually I had different yaml file and I can even work next v12.3.0. I want to work with next v13. By the way how many minutes does the build take to finish build for this yml. I curried about it. My yaml takes 15 mins for each build
Yes, that's one downside of for amplify and nextjs, it takes a lot of time to compile for me the average is 20mins to complete, is really painful.
Can you please share your yaml to see if it works for me?
@manxon Sure bro. This YAML workflow takes 15mins for my 3 projects. And it works until next@12.3.0. You do not need to do anything. Delete your outputFileTracingRoot from your next.config.js and try it. Here is the code;
version: 1
applications:
- appRoot: apps/your-app-name
frontend:
phases:
build:
commands:
- cd ../../
- yarn
- npx nx run your-app-name:build:production
- cp -R dist/apps/your-app-name/.next apps/your-app-name
- cp -R node_modules apps/your-app-name
- cd apps/your-app-name
artifacts:
baseDirectory: .next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
I am still having problems running nx/nextjs on amplify
we're successfully deploy
nx
to amplify using this approach
- using standalone build with monorepo configurations
// apps/web-app/next.config.js module.exports = { output: 'standalone', experimental: { // this includes files from the monorepo base two directories up outputFileTracingRoot: path.join(__dirname, '../../'), }, }
- on build steps, we move standalone builds from basedir to standalone directory, then replace relative path from
distDir
onserver.js
version: 1 applications: - frontend: phases: preBuild: commands: - yarn install build: commands: - npx nx run web-app:build:production - mv ./dist/apps/web-app/.next/standalone/apps/web-app/* ./dist/apps/web-app/.next/standalone/ - sed -i 's/\/..\/..//' ./dist/apps/web-app/.next/standalone/server.js artifacts: baseDirectory: dist/apps/web-app/.next files: - '**/*' cache: paths: - node_modules/**/*
works like charms
"nx": "15.8.5", "next": "13.1.1",
This one worked for me, I just had to copy the public folder as well :1st_place_medal:
we're successfully deploy
nx
to amplify using this approach
- using standalone build with monorepo configurations
// apps/web-app/next.config.js module.exports = { output: 'standalone', experimental: { // this includes files from the monorepo base two directories up outputFileTracingRoot: path.join(__dirname, '../../'), }, }
- on build steps, we move standalone builds from basedir to standalone directory, then replace relative path from
distDir
onserver.js
version: 1 applications: - frontend: phases: preBuild: commands: - yarn install build: commands: - npx nx run web-app:build:production - mv ./dist/apps/web-app/.next/standalone/apps/web-app/* ./dist/apps/web-app/.next/standalone/ - sed -i 's/\/..\/..//' ./dist/apps/web-app/.next/standalone/server.js artifacts: baseDirectory: dist/apps/web-app/.next files: - '**/*' cache: paths: - node_modules/**/*
works like charms
"nx": "15.8.5", "next": "13.1.1",
This one worked for me, I just had to copy the public folder as well π₯
I'm using the same schema in our production environment but are unable to take advantage of ISR because it seems next creates the regenerated data into the incorrect folder does anyone know how or if it's possible to work around this issue?
"next": "13.1.1"
Does anyone else get the backend
build step failing despite not having a backend set up?
NX 15.9.2 NextJS 13.2.2
version: 1
applications:
- appRoot: apps/web
frontend:
phases:
preBuild:
commands:
- cd ../../
- echo "Installing NPM packages"
- npm install
build:
commands:
- echo "Building web application"
- npx nx build web --verbose
- echo "So that went through, CDing back to app's root directory"
- cd apps/web
postBuild:
commands:
- echo "Moving and removing folders"
- mv -f ../../dist/apps/web/.next/standalone/apps/web/* ../../dist/apps/web/.next/standalone
- sed -i 's/\/..\/..//' ../../dist/apps/web/.next/standalone/server.js
artifacts:
baseDirectory: dist/apps/web/.next
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Tried redeploying a commit that successfully deployed 2 months ago - fails with the same error. Any advice would be much appreciated!
Hi,
We have provided the support for NextJs Web Compute + Monorepo frameworks
FAQ link: https://github.com/aws-amplify/amplify-hosting/blob/main/FAQ.md#support-for-monorepo-framework
Please feel free to create new issue if you have additional question.
Thanks
Comments on closed issues are hard for our team to see. If you need more assistance, please either tag a team member or open a new issue that references this one. If you wish to keep having a conversation with other community members under this issue feel free to do so.
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Describe the bug I'm trying to deploy a NX Nextsj monorepo to amplify. NX is a monorepo tool and its designed around using 1 package json and node_modules. If managed to build the app with a custom amplify yml, and I'm now at the point the build passes but the deployment fails. After 9 days of going at this I'm really lost.
The error I get is:
And my amplify YML config is
I originally had it build in th apps/appname directory like people mentioned but that just throws a exit code for /.bin/next build.