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

Adding Amplify Auth to a Next.js project has a huge impact of the chunk size #7570

Closed
Riley0111 opened this issue Jan 18, 2021 · 72 comments · Fixed by #7842 or #8626
Closed

Adding Amplify Auth to a Next.js project has a huge impact of the chunk size #7570

Riley0111 opened this issue Jan 18, 2021 · 72 comments · Fixed by #7842 or #8626
Labels
Auth Related to Auth components/category Build Related to build issues feature-request Request a new feature SSR Issues related to Server Side Rendering

Comments

@Riley0111
Copy link

Riley0111 commented Jan 18, 2021

Describe the bug
I want to use Amplify Auth with my Next.js project. After I added aws-amplify to my project and imported 'Auth' to my index page the First load size increased from 64.1 kB to 308 kB without adding anything else. I also tried to analyze the problem with the webpack-bundle-analyzer and noticed that a lot of crypto libraries got loaded and some of them like bn.js multiple times (see screenshot below).

To Reproduce

  1. Create a new Next.js project
  2. Add aws-amplify to your package.json
  3. import {Auth} from 'aws-amplify'; in your index.js page

Expected behavior
That the use of the aws-amplify Auth module will add way less than 240 kB to the first load size. Or is this an expected increase of size?

Code Snippet

package.json:

"dependencies": {
    "next": "^10.0.5",
    "react": "16.14.0",
    "react-dom": "16.14.0",
    "aws-amplify": "3.3.14"
  },

index.js

import Head from 'next/head'
import {Auth} from 'aws-amplify';

export default function Home() {
    Auth.currentAuthenticatedUser()

    return (
        <div className="container">
            <Head>
                <title>Create Next App</title>
                <link rel="icon" href="/favicon.ico"/>
            </Head>

            <main>
                <h1 className="title">
                    Welcome to <a href="https://nextjs.org">Next.js!</a>
                </h1>
            </main>
        </div>
    )
}

Screenshots
Screenshot from the webpack bundle analyzer:
Bildschirmfoto 2021-01-18 um 10 33 16

Page size without amplify:
Bildschirmfoto 2021-01-18 um 10 44 11

Page size with amplify:
Bildschirmfoto 2021-01-18 um 10 43 57

What is Configured?
Amplify version: 3.3.14
Next.js version: 10.0.5

@Riley0111 Riley0111 added the to-be-reproduced Used in order for Amplify to reproduce said issue label Jan 18, 2021
@jamessouth
Copy link

Dumping the amplify package might help, see #7313 (comment)

@iartemiev iartemiev added the SSR Issues related to Server Side Rendering label Jan 19, 2021
@amhinson
Copy link
Contributor

This looks to be related to #7521, which has been merged but not released yet. We will likely be doing a release this week. However, you can test out the changes currently in main by using aws-amplify@unstable.

@amhinson amhinson added pending-close-response-required and removed to-be-reproduced Used in order for Amplify to reproduce said issue labels Jan 19, 2021
@Riley0111
Copy link
Author

Riley0111 commented Jan 19, 2021

I just tested using @aws-amplify/auth instead of importing from aws-amplify but it only reduced the first load size from 308kB to 306 kB.

I also tried with "aws-amplify": "3.3.15-unstable.3" but it doesn't have any effect at the first load size or the webpack bundle analyzer.

@amhinson
Copy link
Contributor

Ah yes, sorry, I forgot that the PR only addressed a usage with Create React App. I'll do a bit more digging and testing and get back to you 👍

@ericclemmons ericclemmons mentioned this issue Jan 19, 2021
2 tasks
@ericclemmons
Copy link
Contributor

We definitely need to investigate this more, particularly for Next.js.

Next.js is moving to support Webpack 5, but explicitly adds a polyfill for crypto (that webpack4 does automatically):

https://github.com/vercel/next.js/blob/0d0db45c7201acf850b01343a846e0a74db86d77/packages/next/build/webpack-config.ts#L377

Next.js' "base bundle" size is around 65kB, and using import { Amplify, Auth } from "aws-amplify" brought it up to ~205kB.

We'd like to get this lower, of course, knowing that we don't want crypto polyfilled on the client, but this needs work on top of #7521 to accomplish.

@ianpogi5
Copy link

This looks to be related to #7521, which has been merged but not released yet. We will likely be doing a release this week. However, you can test out the changes currently in main by using aws-amplify@unstable.

I just tried "aws-amplify": "^3.3.15-unstable.3" on my react app and can confirm that the size has been drastically reduced.

@ericclemmons
Copy link
Contributor

@ianpogi5 That's great news! I'll share it with @amhinson 💪

Is it a Next.js app or Create React App?

@ianpogi5
Copy link

@ianpogi5 That's great news! I'll share it with @amhinson 💪

Is it a Next.js app or Create React App?

It's CRA

@bezreyhan
Copy link

This is also a big issue for us as our bundle size has increased dramatically.

@hwangar
Copy link

hwangar commented Jan 26, 2021

Same issue here, even with 3.3.15-unstable.8:
image

Multiple duplications in the bundle (7x bn.js 85Kb... unnecessary ~510Kb for a "hello world app")

In case it helps, not my first time with this issue: in another project I decided to downgrade "crypto-js@4"... for me the root of all evil, to "^3.1.9-1" and all bundle issues vanished

@VicFrolov
Copy link

Confirming this is also an issue with latest "@aws-amplify/auth": "3.4.17" for us

@bezreyhan
Copy link

Has there been any progress or update on this issue? This issue is really slowing down our site.

Alternatively, is there documentation on how to use Cognito without Amplify?

@VicFrolov
Copy link

Any updates?

@fomalhaut79
Copy link

Same issue here with the new Vue project after import Auth from "@aws-amplify/auth"
Screen Shot 2021-02-24 at 9 01 49 AM

@bobbyhadz
Copy link

bobbyhadz commented Feb 25, 2021

Same issue, amplify is absolutely unusable with next.js with first load of 300 kB for just including an @aws-amplify/auth import.

The same module gets loaded like 8 times.

Can we get an update from the amplify team, I mean this is not really a corner case issue, Next.js is one of the most popular react frameworks. Is this being worked on?

The amplify team say they're working on deploying next.js applications using amplify, I mean that's great and very exciting, but maybe a priority should be to not load over 300kb of gzipped code for the auth module.

Also didn't realize about this until I finished building the site, that's not very fun.

@o-gi
Copy link

o-gi commented Mar 1, 2021

I'm curious if there are any updates to this.I think it's safe to say that using Nextjs to create Jamstack is now the standard.This is a pretty important issue.

@VicFrolov
Copy link

Words cannot explain how continuously disappointed I am with the Amplify team's lack of responses on a wide net of outstanding issues such as this one.

@sammartinez sammartinez added the to-be-reproduced Used in order for Amplify to reproduce said issue label Mar 1, 2021
@ericclemmons ericclemmons added this to the Bundle Size Optimizations milestone Mar 1, 2021
@ericclemmons
Copy link
Contributor

Hey everyone, I'm personally sorry for the late resolution here.

With bundle sizes improved via #7521, I missed that Next.js doesn't resolve .web.js files (vercel/next.js#1854).

I opened a PR with my research, tests to alert us on bundle-size increases (so bloat doesn't happen accidentally), and possible solutions. I'd really appreciate your input here:

#7842

For an immediate workaround, you can opt-in to the .web.js files from #7521, which will prevent crypto polyfills from being included in your browser bundle:

--- a/samples/next/auth/ssr-auth/next.config.js
+++ b/samples/next/auth/ssr-auth/next.config.js
@@ -1,3 +1,8 @@
 module.exports = {
   target: 'serverless',
+  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
+    config.resolve.extensions = ['.web.js', ...config.resolve.extensions]
+
+    return config
+  },
 }

The results are:

Page                                                           Size     First Load JS
┌ ○ /                                                          3.47 kB        66.2 kB
├   /_app                                                      0 B            62.7 kB
├ ○ /404                                                       3.46 kB        66.2 kB
├ ○ /Amplify                                                   875 B          67.4 kB
├ ○ /Amplify+Auth                                              37.9 kB         142 kB
├ ○ /Amplify+Storage                                           42.6 kB         146 kB
└ λ /api/hello                                                 0 B            62.7 kB
+ First Load JS shared by all                                  62.7 kB
  ├ chunks/f6078781a05fe1bcb0902d23dbbb2662c8d200b3.015d8f.js  13.1 kB
  ├ chunks/framework.e2fe4a.js                                 41.8 kB
  ├ chunks/main.a1fab4.js                                      6.62 kB
  ├ chunks/pages/_app.3da7c8.js                                530 B
  ├ chunks/webpack.50bee0.js                                   751 B
  └ css/2f26bb9842d84a608fa3.css                               202 B

Down to 142kB from 281kB (-138kB). For comparison, Next.js has a ~65kB "tax" just to run "Hello World". This puts the Amplify+Auth.js page at ~77kB additional, which is comparable to Create React App's ~75kB. (See #7842 for more numbers)

I also created a Bundle Size Optimizations milestone to track these issues & get them released once we validate Next.js + Amplify continues working as intended 🙏

@o-gi
Copy link

o-gi commented Mar 2, 2021

@ericclemmons I’m grateful for all your help

@izzy-h
Copy link

izzy-h commented Mar 2, 2021

Hi @ericclemmons, thanks for sharing this. Do you have any ideas as to why this solution wouldn’t work with other react frameworks? I created a brand new Gatsby project and added Auth as a dependency, and also configured webpack to resolve .web.js files, but am still seeing the crypto polyfills included in the bundle.

Dependency in package.json:

"@aws-amplify/auth": "^3.4.24"

Importing Auth in gatsby-browser.js:

import { Auth } from "@aws-amplify/auth";

Configuring webpack in gatsby-node.js:

exports.onCreateWebpackConfig = ({ actions }) => {
    actions.setWebpackConfig({
        resolve: {
            extensions: ['.web.js']
        },
    })
}

However, as you can see from the bundle analyser output, all those crypto modules are still being included:

image

Any ideas as to how to exclude them? Thanks

@ericclemmons
Copy link
Contributor

@izzy-h I'm looking into "browser": { "crypto": false } behavior for Gatsby right now in #7842.

By default, I get:

warn Module not found: Error: Can't resolve 'crypto' in '/Users/ecclemm/Projects/ericclemmons/amplify-js/.github/actions/bundle-size-action/gatsby/node_modules/amazon-cognito-identity-js/es/utils'
BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.

If you want to include a polyfill, you need to:
	- add a fallback 'resolve.fallback: { "crypto": require.resolve("crypto-browserify") }'
	- install 'crypto-browserify'
If you don't want to include a polyfill, you can use an empty module like this:
	resolve.fallback: { "crypto": false }

If you could provide a working Gatsby repo with Amplify & Auth to model after, I'd appreciate it! We may have to solve that separately if #7842 doesn't fix Gatsby as well...

@riceboyler
Copy link

riceboyler commented Sep 29, 2021

Can part of that deeper dive mentioned above include figuring out why using the @aws-amplify specific libraries (i.e. @aws-amplify/core, @aws-amplify/analytics, etc.) causes an error related to credentials, region or appid that is only resolved by using aws-amplify (the full library) instead? (FWIW, I dug into that error specifically, and it appears that for some reason, using @aws-amplify/core, the credentials never get passed through, while with aws-amplify they do.

@podlebar
Copy link

podlebar commented Nov 5, 2021

btw.. the same happens if you are using NuxtJS.
import Auth from '@aws-amplify/auth' adds 73.5 kb gziped to the bundle..

@jonas-scholz-obeyo
Copy link

Hey, is there any update on this? I'm using nextjs 12 with aws-amplify and aws-amplify-react (for Authenticator), and it adds 150kb to the first load. Is there anything that I can do to reduce that?

@fgiopp
Copy link

fgiopp commented Feb 24, 2022

I have the same problem reported by riceboyler: @aws-amplify/core, @aws-amplify/API/Storage, etc. causes an error related to credentials, region or appid that is only resolved by using aws-amplify (the full library).

Any update on this? I'm using Nextjs 12.

@aws-eddy aws-eddy removed their assignment Feb 24, 2022
@abdallahshaban557 abdallahshaban557 added the Auth Related to Auth components/category label Jun 3, 2022
@abdallahshaban557
Copy link
Contributor

Hello everyone, we are investigating this issue further on our end. We will provide feedback once we have some next steps.

@rnrnstar2
Copy link

Hi.
I am also facing this problem.
It consumes a fairly large bundle size.
The following code cannot be removed because withSSRContext is not separated from aws-amplify.

import { withSSRContext } from 'aws-amplify/lib-esm';

スクリーンショット 2022-06-22 20 26 02

@rob1121
Copy link

rob1121 commented Jul 15, 2022

Same issue Ive encountered on my nextjs project using @aws-amplify. I unable to get crendentials. Do we have any update on this?

@ivanjd
Copy link

ivanjd commented Sep 1, 2022

This is a pretty annoying problem. None of the proposed solutions worked for us (we are on Next 12.2). Any updates will be highly appreciated.

@abdallahshaban557
Copy link
Contributor

Hello everyone, we have a tagged release that we are testing out that has bundle size reductions which also include removing the crypto libraries for NextJS apps. Could you try this tagged release and inform us if it reduces the bundle size for you - and what that reduction number look like to you?

In order to use this version, you can run the following command in your terminal:
npm install aws-amplify@size-improvement

Reducing the bundle size is one of our highest priority - and your feedback would be so helpful to help us drive enhancements in that area!

@shubhamsharma98
Copy link

Tried but no luck. The chunk sizer is absurdly high! Not sure how its building up this big. This is running in Chrome.

CleanShot 2022-09-12 at 14 30 37@2x

@abdallahshaban557
Copy link
Contributor

@shubhamsharma98 - is this after doing a production build? Or were you still debugging this? The size here is definitely much larger than we expect it to be.

@shubhamsharma98
Copy link

Still in debugging, I'm a bit away from running the app in production but the numbers don't look very promising to go into production as-is. Any tips?

@elie222
Copy link

elie222 commented Oct 2, 2022

Still in debugging, I'm a bit away from running the app in production but the numbers don't look very promising to go into production as-is. Any tips?

Tip is to run a production build and then look at the numbers 😂 You can run the production build today. You don't need to wait for the app to go live. In Next it would be: next build

@shubhamsharma98
Copy link

@elie222 thanks for the tip. I'm new to this so perhaps that's why it was amusing to you but I'll do that and revert with my findings.

@dr-star
Copy link

dr-star commented Jan 4, 2023

Hello everyone, we have a tagged release that we are testing out that has bundle size reductions which also include removing the crypto libraries for NextJS apps. Could you try this tagged release and inform us if it reduces the bundle size for you - and what that reduction number look like to you?

In order to use this version, you can run the following command in your terminal: npm install aws-amplify@size-improvement

Reducing the bundle size is one of our highest priority - and your feedback would be so helpful to help us drive enhancements in that area!

Are you planning to introduce the optimization version also for amplify v5?

@abdallahshaban557
Copy link
Contributor

@dr-star - the optimization was released with V5! You can try it now.

@adarsh-drishya
Copy link

image
Hi @abdallahshaban557 ,what do you say of this? how do i optimize it. as my development has be slow for a long time now. Below are the packages i am using from amplify in my Nextjs project
"@aws-amplify/api": "5.0.9",
"@aws-amplify/auth": "5.0.2",
"@aws-amplify/cache": "5.0.11",
"@aws-amplify/core": "5.0.11",
"@aws-amplify/storage": "5.0.9",

@tannerabread tannerabread added Build Related to build issues feature-request Request a new feature and removed backlog labels Mar 6, 2023
@Dizzzmas
Copy link

photo_2023-03-14 20 59 10
Experienced the same issue with my Next app today. I was hoping to use aws-amplify and @aws-amplify/ui-react to integrate Cognito Auth into my frontend quickly.
Unfortunately, this issue makes amplify unusable for our team.

@abdallahshaban557
Copy link
Contributor

Hello everybody, our team has been focusing on reducing the bundle size of the Amplify library, and starting v 5.2.5, we have been able to reduce the bundle size for the below use cases:

    * Amplify core + Auth category: 73kB → 54kB (-26%)
    * Amplify core + Analytics category: 56kB → 30kB (-46%)

This is only the first step in our bundle size reduction efforts. In our next major version of Amplify JavaScript, we are going to provide better mechanisms for tree-shaking that will substantially reduce the bundle size. Stay tuned - we will provide updates on this issue when we have expected timelines mapped out.

Please try out the newest version of Amplify, and let us know if you are seeing the improvements I've mentioned! Your feedback is essential to helping us improve our library!

@GriffinSauce
Copy link

Still in debugging, I'm a bit away from running the app in production but the numbers don't look very promising to go into production as-is. Any tips?

Tip is to run a production build and then look at the numbers 😂 You can run the production build today. You don't need to wait for the app to go live. In Next it would be: next build

To be fair here: adding Amplify, Auth and Storage balloons the dev chunks by 5 MB. Even if that doesn't have impact on users it does have impact on DX and burns dev time.

@abdallahshaban557
Copy link
Contributor

Hello @GriffinSauce - as part of our next major version, we are planning to substantially reduce the installation and bundle size for Amplify, both client and server side if you are building with NextJS. You can learn more about our areas of focus here.

You can also provide us with feedback here if there are other things you are interested in seeing from Amplify JavaScript! #11833

@cwomack
Copy link
Member

cwomack commented Nov 16, 2023

With the release of the latest major version of Amplify (aws-amplify@>6), this issue should now be resolved! Please refer to our release announcement, migration guide, and documentation for more information.

@cwomack cwomack closed this as completed Nov 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Auth Related to Auth components/category Build Related to build issues feature-request Request a new feature SSR Issues related to Server Side Rendering
Projects
None yet