reactjsamazon-web-servicesaws-sdkaws-sdk-js

AWS SDK Javascript v3 needing Node polyfills


I'm trying to use AWS Translate in my React app, and it seems to be needing a lot of Node polyfills. Is the AWS SDK intended for Node.js use only or do I just need to install like 12 polyfills? The AWS docs I'm looking at seem to indicate it can be used with client-side React code just fine, and I don't see any notes about polyfills or browser workarounds.

The import:

import { TranslateClient, TranslateTextCommand } from '@aws-sdk/client-translate';

Here is one of 24 similar errors I'm seeing when I install and compile:

ERROR in ./node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js 7:15-30
Module not found: Error: Can't resolve 'util' in 'node_modules/@smithy/util-stream/dist-cjs'

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: { "util": require.resolve("util/") }'
        - install 'util'
If you don't want to include a polyfill, you can use an empty module like this:
        resolve.fallback: { "util": false }
 @ ./node_modules/@smithy/util-stream/dist-cjs/index.js 81:24-55
 @ ./node_modules/@smithy/smithy-client/dist-cjs/index.js 134:25-55
 @ ./node_modules/@aws-sdk/client-translate/dist-cjs/index.js 121:27-59
 @ ./app/utils/AmazonTranslate.js 12:0-82 65:23-38 77:30-50

webpack compiled with 24 errors

If I add the following to my webpack config:

fallback: {
    child_process: false,
    crypto: false,
    fs: false,
    http: false,
    http2: false,
    https: false,
    os: false,
    path: false,
    process: false,
    stream: false,
    url: false,
    util: false
}

it compiles without errors, but then I get this when I try and execute the code:

TypeError: Cannot destructure property 'readFile' of 'fs_1.promises' as it is undefined.

I've also tried installing node-polyfill-webpack-plugin, but 6 errors remain involving fs, child_process, and http2.


Solution

  • The AWS Translate SDK is designed with Node.js streaming capabilities in mind, which are not natively supported in the browser environment. While the web relies on technologies like WebSockets, Node.js uses its own streaming modules.

    For web applications, it’s common practice to use an intermediary server to interact with AWS services. This approach not only avoids exposing sensitive credentials on the client side but also circumvents the need for Node-specific polyfills. Although there are scenarios where embedding sensitive information in a locally hosted web app might be acceptable, AWS primarily targets use cases that involve server-side interactions, which may explain the lack of support for direct client-side usage in some SDK clients.