Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server-side rendering support / SSR #412

Closed
ChristopheBougere opened this issue Feb 6, 2020 · 84 comments
Closed

Server-side rendering support / SSR #412

ChristopheBougere opened this issue Feb 6, 2020 · 84 comments
Labels
archived This issue has been locked. feature-request New feature or request

Comments

@ChristopheBougere
Copy link

Is your feature request related to a problem? Please describe.
I created a web app using Amplify+React. Now I need to work on the SEO, but this requires server-side rendering (I am using react-helmet-async to change <title> and <meta> tags dynamically, but google and other search engines stick with the static versions in index.html. Note that I can't do static exporting (because my page titles and descriptions depend on data from the API).

Describe the solution you'd like
I would like server-side rendering to be managed by the Amplify Console itself.
Next.js seems to be the best way to do this in React for now, but I would be quite open to other solutions.

Additional context
I don't find any workaround to do SSR with Amplify when using hosting. I could surely do SSR by hosting it on my own S3+CloudFront and maybe adding some lambda@edge, but I would definitely miss the managed hosting benefits.
However, SEO is a very high priority for the next few months, so I will have to find a solution. The easiest alternative as of now would be to use Zeit Now) for hosting, as described in this post

@swaminator swaminator added the feature-request New feature or request label Feb 6, 2020
@sebsto
Copy link

sebsto commented Feb 12, 2020

Christophe, see aws-amplify/amplify-js#1613

@ZachMurray
Copy link

Is your feature request related to a problem? Please describe.
I created a web app using Amplify+React. Now I need to work on the SEO, but this requires server-side rendering (I am using react-helmet-async to change <title> and <meta> tags dynamically, but google and other search engines stick with the static versions in index.html. Note that I can't do static exporting (because my page titles and descriptions depend on data from the API).

Describe the solution you'd like
I would like server-side rendering to be managed by the Amplify Console itself.
Next.js seems to be the best way to do this in React for now, but I would be quite open to other solutions.

Additional context
I don't find any workaround to do SSR with Amplify when using hosting. I could surely do SSR by hosting it on my own S3+CloudFront and maybe adding some lambda@edge, but I would definitely miss the managed hosting benefits.
However, SEO is a very high priority for the next few months, so I will have to find a solution. The easiest alternative as of now would be to use Zeit Now) for hosting, as described in this post

Same Problem I Have.

@agrant-intix
Copy link

agrant-intix commented Jun 19, 2020

@swaminator is there a timeframe on next JS support with Amplify? I note it was added as a feature request on 7 Feb

@ChristopheBougere
Copy link
Author

With Next.js support being in public preview (cf aws-amplify/amplify-js#5435), it would be great to know if we can expect it to be supported by the console as well in the short term (so we can still use amplify hosting with SSR).

@swaminator @ericclemmons do you have any information on this topic?

@Nickman87
Copy link

Still looking for a good all-in hosting system for next.js applications. I was thinking the Amplify system would be a great fit but definitely needs good SSR support for it to be usefull.
Any news on this?

@dabit3
Copy link

dabit3 commented Sep 15, 2020

@Nickman87 Amplify hosting support for SSR is in the works!

In the meantime, you can use the Serverless Next.js Component to deploy Next.js to AWS with SSR and API routes.

Here's how:

  1. Create a file called serverless.yml in the root of your Next.js app
  2. Add the following 2 lines of configuration (version should be updated to the latest stable release, which as of this writing is 1.16.0):
myNextAPp:
  component: "@sls-next/serverless-component@1.16.0
  1. Deploy by running npx serverless.

We will update this once Amplify SSR support is officially launched for the hosting service.

@ericclemmons
Copy link

@Nickman87 Agreed! We have @dabit3's suggestion documented on our Next.js' Getting Started page, including a short video.

I tested it myself & it worked great 💪

@IamManchanda
Copy link

IamManchanda commented Sep 25, 2020

Eagerly awaiting SSR support for AWS Amplify Console for both Next.js (React) & Nuxt.js (Vue) ✈️

@ericclemmons
Copy link

@IamManchanda Me too! :) Can you tell me more about your Next.js app?

  • Are you using getInitialProps?
  • Are you using getServerSideProps?
  • Are you using getStaticProps?
  • Are you using getStaticPaths?
    • Are you using fallback: true or fallback: false?
  • Are you using revalidate at all?
  • Are you using /api/* routes?
  • Are you running next export or only next build?

The more we know about your usage, the better we can support you 💪

@agrant-intix
Copy link

Hi @ericclemmons

Can talk for my next.js project wanting AWS console support.

Are you using getInitialProps? Yes
Are you using getServerSideProps? Yes
Are you using getStaticProps? Not currently
Are you using getStaticPaths? Not currently
Are you using fallback: true or fallback: false? fallback: false
Are you using revalidate at all? No
Are you using /api/* routes? Yes
Are you running next export or only next build? Only next build

@ChristopheBougere
Copy link
Author

ChristopheBougere commented Sep 30, 2020

For anyone interested in making the console deploying the serverless next.js component (waiting for official support), here is the way I did it:

amplify.yml

version: 1
applications:
  - backend:
      phases:
        preBuild:
          commands:
            - nvm use $VERSION_NODE_12
            - npm ci
        build:
          commands:
            - nvm use $VERSION_NODE_DEFAULT
            - amplifyPush --simple
            - nvm use $VERSION_NODE_12
            - npm run build
            - aws s3 sync "s3://your-deployment-bucket/myamazingapp/${USER_BRANCH}/.serverless" .serverless
            - if [ "${USER_BRANCH}" = "staging" ]; then DOMAIN="example.com" SUBDOMAIN="staging" npx serverless ; fi
            - if [ "${USER_BRANCH}" = "prod" ]; then DOMAIN="example.com" SUBDOMAIN="www" npx serverless ; fi
            - aws s3 sync .serverless "s3://your-deployment-bucket/myamazingapp/${USER_BRANCH}/.serverless"
    frontend:
      phases:
        build:
          commands:
            - echo "Nothing to build here"
      artifacts:
        baseDirectory: .next
        files:
          - '**/*'
      cache:
        paths:
          - node_modules/**/*
    appRoot: web

serverless.yml

myamazingapp:
  component: '@sls-next/serverless-component@1.17.0'
  inputs:
    domain:
      - ${env.SUBDOMAIN}
      - ${env.DOMAIN}

A few notes:

  • I'm deploying on 2 different subdomains depending on the $USER_BRANCH env variable. The mapping was previously done using Amplify domains, which are not being used anymore.
  • I had memory issues building my app with node 10, this is why I'm changing to node 12 (except for the amplify push step). But I guess this is optional.
  • The frontend part of the amplify.yml is still present, even though I don't care about what it deploys on https://develop.aaaaaaaaa.amplifyapp.com. AFAIK it is not possible to configure deploying backend only in Amplify Console.

@ericclemmons

  • Are you using getInitialProps? yes
  • Are you using getServerSideProps? yes
  • Are you using getStaticProps? not currently
  • Are you using getStaticPaths? not currently
    • Are you using fallback: true or fallback: false? n/a
    • Are you using revalidate at all? n/a
  • Are you using /api/* routes? Not currently
  • Are you running next export or only next build? next build

@damian-tripbuddi
Copy link

I'm keen to see official support for this. As deploying to Vercel has proved to be challenging when my application is using Amplify. The way that Vercel splits SSG and SSR is amazing, and I hope that we can get the same advantages when Amplify Console has proper support for deploy SSR Next Applications.

@ericclemmons
Copy link

As deploying to Vercel has proved to be challenging when my application is using Amplify.

@damian-tripbuddi If you have more information or suggestions, please share 🙏

@ghost
Copy link

ghost commented Oct 7, 2020

Could someone please update https://aws.amazon.com/blogs/mobile/ssr-support-for-aws-amplify-javascript-libraries/ to change component: "@sls-next/serverless-component@1.16.0" to component: "@sls-next/serverless-component@1.17.0"?

@ChristopheBougere
Copy link
Author

ChristopheBougere commented Oct 19, 2020

As deploying to Vercel has proved to be challenging when my application is using Amplify.

@damian-tripbuddi If you have more information or suggestions, please share 🙏

@ericclemmons
To follow up on this, the current solution using Serverless Next.js component shows huge perfomance issues for SSR and cold starts (the "require JS execution time" to be more specific, see this issue: serverless-nextjs/serverless-next.js#547).
There is a chance this could be linked to my app itself (and accumulation of react HoC), but I wanted to try deploying on Vercel to see if there is a difference.
The thing is I don't want to commit my aws-exports.js file, which is mandatory for the build, and there is no simple way to generate it without setting up all the amplify kit, which indeed can be challenging on Vercel. I guess that might be what @damian-tripbuddi pointed out.

@dabit3
Copy link

dabit3 commented Oct 19, 2020

Thanks @Trevor-mc2, we've updated the post

@JeffWeim
Copy link

@dabit3 - I think some people are viewing your post on dev.to (I did) that mention 1.16.0, might be good to update there as well

Thanks @Trevor-mc2, we've updated the post

@dabit3
Copy link

dabit3 commented Oct 21, 2020

Thanks @JeffWeim, just updated there as well.

@IamManchanda
Copy link

IamManchanda commented Nov 2, 2020

Hey @ericclemmons
Will the AWS Amplify JS + AWS Amplify Console support (SSR) also plans to include
this feature 👇
=> https://nextjs.org/docs/basic-features/image-optimization (released on oct 27)

@tariqinaam
Copy link

tariqinaam commented Nov 9, 2020

@Nickman87 Amplify hosting support for SSR is in the works!

In the meantime, you can use the Serverless Next.js Component to deploy Next.js to AWS with SSR and API routes.

Here's how:

  1. Create a file called serverless.yml in the root of your Next.js app
  2. Add the following 2 lines of configuration (version should be updated to the latest stable release, which as of this writing is 1.16.0):
myNextAPp:
  component: "@sls-next/serverless-component@1.16.0
  1. Deploy by running npx serverless.

We will update this once Amplify SSR support is officially launched for the hosting service.

I am following guide on aws. I was able to run the app locally successfully.
Deployed using above serverless component, cli shows successful deployment. However when visiting the cloudfront app url. I get following error:
The Lambda function associated with the CloudFront distribution is invalid or doesn't have the required permissions. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.

and console response show LambdaExecutionErro

content-length: 1019 content-type: text/html server: CloudFront status: 503 x-cache: LambdaExecutionError from cloudfront

I checked cloudfront UI, deployment was successful and complete.
I am not sure where do i look further to dig in this issue. Any lead would be helpful.|

Update
I can see lambda execution is timing out without any further error. I increases execution to 15 sec, but still timing out.

@ohlr
Copy link

ohlr commented Nov 9, 2020

@tariqinaam you need to redeploy (run serverless) to create the new pages

@tariqinaam
Copy link

@tariqinaam you need to redeploy (run serverless) to create the new pages

It's failing on existing page. E.g homepage which obviously exist

@dmsolutionz
Copy link

@tariqinaam you need to redeploy (run serverless) to create the new pages

It's failing on existing page. E.g homepage which obviously exist

Increase the timeout to 25, try again. It could be the cold start.

@tariqinaam
Copy link

@tariqinaam you need to redeploy (run serverless) to create the new pages

It's failing on existing page. E.g homepage which obviously exist

Increase the timeout to 25, try again. It could be the cold start.

I have increased it to 30sec, but somehow response failing in 10 sec. Is there anything need to be changed to cloudfront side?
One thing I noticed that serverless created cloudfront and lambda in us-east-1 region by default. whereas my application is in eu-west-1 region. could there be any permission issue between regions?

@ixartz
Copy link

ixartz commented May 18, 2021

@andrewbtp Thank you for sharing this awesome news. I'm also waiting this feature for a long time.

Here is the official post: https://aws.amazon.com/about-aws/whats-new/2021/05/aws-amplify-hosting-announces-server-side-rendering-support-for-next-js-web-apps/

@swaminator
Copy link
Contributor

swaminator commented May 18, 2021

As @andrewbtp called out. This feature is now live. Here's a link to the launch blog: https://aws.amazon.com/blogs/mobile/host-a-next-js-ssr-app-with-real-time-data-on-aws-amplify/

We are going to close this issue @ChristopheBougere. For feature requests, bugs, questions please open a new issue. Thanks again for all the folks who participated in the preview phase. You guys are amazing!

@peterwmwong
Copy link

@nimacks @reavis We are hitting the same "AccessDenied" issue...

2021-05-18T19:53:39.654Z [INFO]: Export successful. Files written to /codebuild/output/src404940831/src/sdn-product/tools/upc-tv/out
2021-05-18T19:53:39.666Z [INFO]: Starting SSR Build...
2021-05-18T19:54:47.320Z [INFO]: AccessDenied

What's odd, is on adifferent AWS account with the same exact code (mirrored repository), it works just fine and does not log "Starting SSR Build...".

Any ideas?

@Athena96
Copy link
Contributor

@peterwmwong looks like your app is detected as an SSR app. Please see the docs for how we detect SSR apps. If you continue to face this issue, please open a different GitHub issue. Thanks!

@swaminator
Copy link
Contributor

@peterwmwong (and any new posters) - please file a new issue to receive support. This issue is closed.

@peterwmwong
Copy link

peterwmwong commented May 20, 2021

@swaminator Yup, already done. Anyone else interested, head over to #1854

@sudarshann
Copy link

sudarshann commented May 23, 2021

2021-05-23T11:46:38.872Z [INFO]: Done in 24.98s.
2021-05-23T11:46:38.876Z [INFO]: Starting SSR Build...
2021-05-23T11:47:56.230Z [INFO]: AccessDenied 

I am trying to deploy a starter next js app which I just created and added amplify I get the above error. Everything else deployed perfectly. Even it built successfully. But I get the above error. I have followed all steps as per this https://aws.amazon.com/blogs/mobile/host-a-next-js-ssr-app-with-real-time-data-on-aws-amplify/

I have double checked the IAM role too its perfectly set up with full permission. I think its an issue with configuring cloudfront probably ?

Any clues ?

@Musashi-Sakamoto
Copy link

Musashi-Sakamoto commented May 27, 2021

With no changes in our code or build configuration, all of our builds have started failing with

Starting SSR Build...
AccessDenied

or

Starting SSR Build...
Error

Is it possible that some of the SSR preview functionality was incorrectly applied to our account? I see no configuration options for SSR and we haven't figured out any other way to disable it so we can prevent these errors and get our builds working.

@nimacks
Hi, I have the same problem but only with Starting SSR Build... Error. Can you help me please?

my amplify.yml is below. I'm using serverless-next.

version: 1
backend:
  phases:
    build:
      commands:
        - nvm install $NODE_VERSION
        - nvm use $NODE_VERSION
        - yarn install
        - npm install -g @aws-amplify/cli
        - amplifyPush --simple
        - amplify api gql-compile
        - amplify codegen
        - echo "NODE_ENV=production" >> .env.production
        - echo "NEXT_PUBLIC_FACILITY_FRONTEND=$NEXT_PUBLIC_FACILITY_FRONTEND" >> .env.production
        - aws s3 sync "s3://znoo-serverless-bucket/${AWS_BRANCH}/.serverless" .serverless
        - npx serverless --debug
        - aws s3 sync .serverless "s3://znoo-serverless-bucket/${AWS_BRANCH}/.serverless"
frontend:
  phases:
    build:
      commands:
        - echo "Nothing to build here"
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

@nimacks
Copy link
Contributor

nimacks commented May 27, 2021

With no changes in our code or build configuration, all of our builds have started failing with
Starting SSR Build...
AccessDenied
or
Starting SSR Build...
Error
Is it possible that some of the SSR preview functionality was incorrectly applied to our account? I see no configuration options for SSR and we haven't figured out any other way to disable it so we can prevent these errors and get our builds working.

@nimacks
Hi, I have the same problem but only with Starting SSR Build... Error. Can you help me please?

my amplify.yml is below. I'm using serverless-next.

version: 1
backend:
  phases:
    build:
      commands:
        - nvm install $NODE_VERSION
        - nvm use $NODE_VERSION
        - yarn install
        - npm install -g @aws-amplify/cli
        - amplifyPush --simple
        - amplify api gql-compile
        - amplify codegen
        - echo "NODE_ENV=production" >> .env.production
        - echo "NEXT_PUBLIC_FACILITY_FRONTEND=$NEXT_PUBLIC_FACILITY_FRONTEND" >> .env.production
        - aws s3 sync "s3://znoo-serverless-bucket/${AWS_BRANCH}/.serverless" .serverless
        - npx serverless --debug
        - aws s3 sync .serverless "s3://znoo-serverless-bucket/${AWS_BRANCH}/.serverless"
frontend:
  phases:
    build:
      commands:
        - echo "Nothing to build here"
  artifacts:
    baseDirectory: .next
    files:
      - '**/*'
  cache:
    paths:
      - node_modules/**/*

Can you create a separate issue for this? We're going to investigate.

@Athena96
Copy link
Contributor

@Musashi-Sakamoto if you want to continue with your implementation using serverless then follow the instructions here to configure your app to be detected as SSG.
thanks!

@krikork
Copy link

krikork commented May 29, 2021

Is there an ETA on when amplify will support the Next.js Image component? The current documentation states:

Currently, Amplify doesn’t fully support Image Component and Automatic Image Optimization available in Next.js 10.

@ibrahimcesar
Copy link

I would love to hear an ETA too @krikork . In fact I think is due that officially Next 10.0 is not supported at all. In the public announcement is said:

Amplify Hosting supports all Next.js features in version 9.x.x including SSR API routes, dynamic pages, and automatic pre-rendering.

I think even ISG, delivered in Next 9.3, is not currently working – and I would love to be corrected if I'm wrong on this.

@darwin-luque
Copy link

darwin-luque commented May 29, 2021

@nimacks I'm having the same issue as @reavis. Do you guys have any updates on the matter? Thanks in advance!

I'm using Next v. 9.5.6-canary.18

Edit:
I fixed the issue by assigning to the role the AdministratorAccess-Amplify policy. I just had the AdministratorAccess policy assigned to it. However, this policy has access to everything the Amplify specific one has, I'm not really sure about the difference this made. If someone can chime in, I would appreciate it.

@krikork
Copy link

krikork commented May 31, 2021

Has anyone had any success with next.js api routes using the newly released amplify SSR support? I have the simplest of apis from the nextjs documentation:

export default function handler(req, res) {
    res.status(200).json({ name: 'John Doe' })
};

I get a 503 when invoking the API with the standard "The Lambda function associated with the CloudFront distribution is invalid or doesn't have the required permissions. We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner."

Looking at the lambda logs I see the following for every call:

ERROR	Invoke Error 	{
    "errorType": "Error",
    "errorMessage": "Cannot find module '../../chunks/8806.js'\nRequire stack:\n- /var/task/pages/api/image.js\n- /var/task/index.js\n- /var/runtime/UserFunction.js\n- /var/runtime/index.js",
    "code": "MODULE_NOT_FOUND",
    "requireStack": [
        "/var/task/pages/api/image.js",
        "/var/task/index.js",
        "/var/runtime/UserFunction.js",
        "/var/runtime/index.js"
    ],
    "stack": [
        "Error: Cannot find module '../../chunks/8806.js'",
        "Require stack:",
        "- /var/task/pages/api/image.js",
        "- /var/task/index.js",
        "- /var/runtime/UserFunction.js",
        "- /var/runtime/index.js",
        "    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:815:15)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:667:27)",
        "    at Module.require (internal/modules/cjs/loader.js:887:19)",
        "    at require (internal/modules/cjs/helpers.js:74:18)",
        "    at Object.__webpack_require__.f.require (/var/task/pages/api/image.js:331:28)",
        "    at /var/task/pages/api/image.js:265:40",
        "    at Array.reduce (<anonymous>)",
        "    at Function.__webpack_require__.e (/var/task/pages/api/image.js:264:67)",
        "    at Function.__webpack_require__.x (/var/task/pages/api/image.js:347:33)",
        "    at /var/task/pages/api/image.js:357:57"
    ]
}

from package.json:

"aws-amplify": "^3.4.3",
"next": "^10.2.3",
"@aws-amplify/ui-react": "^1.2.1",

------------------------ UPDATE ------------------------
Downgrading Next to 10.0.5 and setting webpack5: false in the next.config.js did the trick.

@berik
Copy link

berik commented Jun 2, 2021

@ibrahimcesar I am also having issues with ISR (revalidate). ISR is not supported at the moment.

You can try this example in Vercel and AWS amplify. It works in Vercel but not in AWS
nextjs-isr-logrocket-main.zip

@ptejada
Copy link

ptejada commented Jun 13, 2021

@krikork
I was having the same issue and setting the flag webpack5: false fixed the 503 error. I did not had to downgrade the Next library.

The frustrating part is that I was not even able to review any kind of logs. All the Lambda functions logs were empty. I even try enabling the S3 logging for the CloudFront distribution group.

Any insight you can provide on how you got those logs is appreciated. I want to be able to troubleshoot any future issues.

@krikork
Copy link

krikork commented Jun 14, 2021

Hi @ptejada, one way I have found so far is to:

  1. Go to cloudFront in the AWS Console
  2. Click Monitoring (under the telemetry section on the left)
  3. You will see 3 tabs in the monitoring section. Click on "Lambda@Edge"
  4. Select the function you want to explore. (That will enable the "View function metrics" button)
  5. Click "View function metrics". This will load a few charts about your function.
  6. Click the "View function logs" button at the top right. This will give you the regions where your function is running.
  7. I would recommend selecting the one closest to you or your customers. There is no guarantee about the region your call will be routed to so you might have to experiment here with different regions.
  8. That will finally get you to the logs.

This is obviously a very convoluted user experience. I have not had a chance to explore whether there is a more convenient way of aggregating all the logs in a single place. If anyone has any suggestions please share.

@ptejada
Copy link

ptejada commented Jun 15, 2021

@krikork

Thank very much for the detailed steps. Very helpful.

I am quite new to the serverless game. My mistake was assuming Lambda and Lambda@Edge were referencing the same resource. From what I understand now Lambda@Edge are basically clones of the original Lambda function but in different regions.

@haderman
Copy link

@krikork I applied your suggestion and it's working for me, thanks!

the only thing is that I am trying to set an env variable in the lambda function (configuration -> env variables - add) but it's returning undefined when I call it like process.env.ANYTHING. has someone had this problem?

@mionch-og
Copy link

Hey @haderman unfortunately due to how they work, Lambda@Edge functions do not support the use of environment variables and attaching them to a Cloudfront distribution requires them to be deployed at Edge. From what I know other solutions either put such config in SSM or an S3 bucket or generate additional lambdas for SSR, where the one requiring environment variables has them set, but they are not deployed @edge, instead it is accessed through API Gateway. Both solutions would probably be hard to implement with Amplify however.
One thing I'd look into would be maybe generating a .env file in the build section of your application - as this way the lambda will have the dotenv and the build script should have your variables set.

@sakhmedbayev
Copy link

Wow! Spent like 3 days realizing that Lambda@Edge functions do not support system variables. So frustrating, why it is not spelled out anywhere in the docs??? :-(

@mionch-og, thanks for the explanation! Can you please provide more detailed instruction on this?

One thing I'd look into would be maybe generating a .env file in the build section of your application - as this way the lambda will have the dotenv and the build script should have your variables set.

@github-actions
Copy link

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.

@github-actions github-actions bot added the archived This issue has been locked. label Oct 28, 2022
@github-actions github-actions bot locked and limited conversation to collaborators Oct 28, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
archived This issue has been locked. feature-request New feature or request
Projects
None yet
Development

No branches or pull requests