question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Server-Side Rendering (SSR) with Next.js

See original GitHub issue

Given Next.js’ popularity, customer impact, and being a hybrid framework supporting both SSR & SSG, solving for Next.js first unblocks other frameworks (e.g. Gatsby, Nuxt).

There is additional work to be done for CLI & Console support (particularly around deployments), but this Epic focuses on JS support.

This feature is live! See the Getting Started tutorial and SSR docs for the latest!

Public Preview

We’d love your help testing out Amplify’s API, Auth, and DataStore categories in your Next.js app!

  1. First, reinstall Amplify using the @preview tag on NPM:

    yarn add aws-amplify@preview
    # or
    npm install aws-amplify@preview --save
    
  2. If you’re only accessing public data (e.g. API.graphql(listBlogs)), you’re done! 😌

  3. For secure access the current user on the server, you’ll need to scope Amplify to the current request (and only that request) using our new withSSRContext helper:

    diff --git a/my-next-app/pages/index.tsx b/my-next-app/pages/index.tsx
    index 22b0c471..d7ce454b 100644
    --- a/my-next-app/pages/index.tsx
    +++ b/my-next-app/pages/index.tsx
    @@ -1,6 +1,6 @@
     import { CognitoUser } from '@aws-amplify/auth'
     import { GRAPHQL_AUTH_MODE } from '@aws-amplify/api-graphql'
    -import { Amplify, API, Auth } from 'aws-amplify'
    +import { Amplify, withSSRContext } from 'aws-amplify'
     import { Authenticator } from 'aws-amplify-react'
     import { GetServerSideProps } from 'next'
     import Head from 'next/head'
    @@ -13,8 +13,6 @@ import { CreateTodoMutationVariables } from '../src/API'
    
     Amplify.configure(awsconfig)
    
     // 👇 Your frontend code is now "SSR-aware", giving the backend access to the current session
    +const { Auth, API } = withSSRContext()
    +
     export default function Home(props) {
    @@ -392,8 +390,6 @@ export default function Home(props: Props) {
     }
    
     export const getServerSideProps: GetServerSideProps = async (context) => {
       // 👇 Auth & API are now scoped to the _current_ user's session
    +  const { Auth, API } = withSSRContext(context)
    +
    

    For more information on withSSRContext, see https://github.com/aws-amplify/amplify-js/pull/6146.

  4. Last step! Let us know your experience in the comments below 👇

Milestones

  • SSR withAuthenticator (#5138)

    aws-amplify-react and @aws-amplify/ui-react should at least render withAuthenticator and <AmplifyAuthenticator /> on the server. This was previously blocked by an import "...css", but with Amplify v3 this was moved to customer apps to import.

    This doesn’t mean session state yet, but unblocking the SSR process.

  • SSG with API

    Support API calls (e.g. GraphQLAPI.graphql(...)) in getStaticProps.

  • SSR with API

    Support API calls (e.g. GraphQLAPI.graphql(...)) in getServerSideProps.

  • Next.js /pages/api/* routes with API

    Similar to SSG & SSR, these routes are lambdas that need to support API.graphql calls.

  • SSR with Auth (#5710)

    Support shared client & server state so that authentication flows on the client share credentials with the server (via a subset of cookies). Calls to Auth.currentAuthenticatedUser() should succeed on the server the same way they do on the client.

  • SSR with DataStore (#5450)

    DataStore needs special attention (due to WebSockets) to work on the server, and calls to DataStore.query have to wait for the sync process to complete (otherwise results are initially empty).

  • [ ] SSR with Analytics (https://github.com/aws-amplify/amplify-js/issues/6208)

  • withSSRContext (https://github.com/aws-amplify/amplify-js/pull/6146)


Related milestone: https://github.com/aws-amplify/amplify-js/milestone/26 Related issues: #5101, #4178, #3741, #1613, #3278, #5121, #5097, #4972, #2230, #4990, #4851, #5293, #5435, #5322, #3854, #3053, #3348, #5138, #4311, #4305, #4207, #3037, #992

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:90
  • Comments:108 (31 by maintainers)

github_iconTop GitHub Comments

54reactions
ericclemmonscommented, Sep 15, 2020

👋 Hi everyone!

Today, I’m proud to say that we’ve officially released SSR support for Amplify JS!

What’s changed?

There have been a few changes since aws-amplify@preview was published (see the resources above for more):

  1. Configure your application with Amplify.configure({ ...awsExports, ssr: true }) so that it’s “SSR-aware”.

  2. Client-side code should stay the same as before:

    import { Amplify, API } from "aws-amplify"`;
    
    ...
    const { data } = await API.graphql({ query, variables })
    

    Using withSSRContext on the client will hurt client-side bundle sizes!

  3. Server-side code should use the new withSSRContext utility:

    import { Amplify, withSSRContext } from "aws-amplify";
    ...
    export async function getServerSideProps({ req }) {
    	const SSR = withSSRContext({ req });
    	const { data } = await SSR.API.graphql({ query, variables });
    	...
    

    withSSRContext creates a new copy of Amplify that’s scoped to a single request (including credentials!).

Check out the Getting Started tutorial for a working example of this usage!

What about deployment?

If you’re site is fully static (no getServerSideProps), you can continue using Amplify Console!

However, if you’re using getServerSideProps or fallback: true, there are other options:

- Until [Amplify Console supports SSR](https://github.com/aws-amplify/amplify-console/issues/412) (be sure to upvote & comment!), we've used & tested [deploying with serverless framework](https://docs.amplify.aws/start/getting-started/hosting/q/integration/next).
- Of course, several customers are [deploying with Vercel](https://nextjs.org/docs/deployment) and that should continue working, too.

What’s next?

With today’s announcement, API (both GraphQL & REST), Auth, and DataStore are supported.

These features should also work with other frameworks (such as Nuxt.js & Gatsby), but we trust and rely on your input to make it even better.

The same goes for other features that didn’t make it to release today (e.g. Analytics, Storage, etc.). Please share SSR-specific use-cases for those categories in a new issue on how Amplify can be better experience, and we’ll be happy to help!

With that, I want to personally thank everyone on this issue for your feedback and effort. I’m thrilled that I could play a part in bringing Next.js support to Amplify JS, and want to continue working with y’all to make it even better!

Thanks!

23reactions
ericclemmonscommented, Jul 8, 2020

@apoorvmote You can continue following & commenting on this issue for progress: we’ll update this once it’s on latest.

🎉 Good news though! I just shipped a Next.js preview to aws-amplify@preview!

I’ve updated the description at the top (https://github.com/aws-amplify/amplify-js/issues/5435) with steps to get started. Auth, API, and DataStore are actively developed against, but I’m tracking other categories at the top as well.

Give it a go in your app & comment below on your experience 👇

Read more comments on GitHub >

github_iconTop Results From Across the Web

Basic Features: Pages - Next.js
Also referred to as "SSR" or "Dynamic Rendering". If a page uses Server-side Rendering, the page HTML is generated on each request. To...
Read more >
Server-Side Rendering With Next.js | by Prateek Vijayvergiya
When a user request a webpage, server prepares the page by fetching user-specific data and sends it to the user's machine. The browser...
Read more >
Server-Side Rendering in React using Next.js – How it Works ...
Server -side rendering with JavaScript libraries like React is where the server returns a ready-to-render HTML page and the JS scripts required ...
Read more >
Why we love Next.js and server-side rendering
Next.js allows you to build a React app and render the content on the server in advance. After the initial load is finished,...
Read more >
Implementing SSR in Next.js: Dynamic routing and prefetching
Next.js is a React framework that addresses common pain points developers face when building web applications. From ensuring all your code is ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found