简体   繁体   English

如何在 NextJS 中设置 AWS-SDK 凭证

[英]How to setup AWS-SDK credentials in NextJS

I need to upload some files to S3 from a NextJs application.我需要从 NextJs 应用程序将一些文件上传到 S3。 Since it is server side I am under the impression simply setting environment variables should work but it doesn't.由于它是服务器端,我的印象是简单地设置环境变量应该有效,但事实并非如此。 I know there are other alternative like assigning a role to EC2 but I want to use accessKeyID and secretKey.我知道还有其他选择,比如为 EC2 分配角色,但我想使用 accessKeyID 和 secretKey。

This is my next.config.js这是我的next.config.js

module.exports = {
  env: {
    //..others
    AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID
  },
  serverRuntimeConfig: {
    //..others
    AWS_SECRET_ACCESS_KEY: process.env.AWS_SECRET_ACCESS_KEY
  }
}

This is my config/index.js这是我的config/index.js

export default {
  //...others
  awsClientID: process.env. AWS_ACCESS_KEY_ID,
  awsClientSecret: process.env.AWS_SECRET_ACCESS_KEY
}

This is how I use in my code:这就是我在代码中使用的方式:

import AWS from 'aws-sdk'
import config from '../config'

AWS.config.update({
  accessKeyId: config.awsClientID,
  secretAccessKey: config.awsClientSecret,
});

const S3 = new AWS.S3()

const params = {
  Bucket: "bucketName",
  Key: "some key",
  Body: fileObject,
  ContentType: fileObject.type,
  ACL: 'public-read'
}

await S3.upload(params).promise()

I am getting this error: Unhandled Rejection (CredentialsError): Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1我收到此错误:未处理的拒绝(CredentialsError):配置中缺少凭据,如果使用 AWS_CONFIG_FILE,请设置 AWS_SDK_LOAD_CONFIG=1

If I hard code the credentials in code, it works fine.如果我在代码中对凭据进行硬编码,它就可以正常工作。

How can I make it work correctly?我怎样才能让它正常工作?

Looks like the Vercel docs are currently outdated (AWS SDK V2 instead of V3).看起来 Vercel 文档目前已过时(AWS SDK V2 而不是 V3)。 You can pass the credentials object to the AWS service when you instantiate it.您可以在实例化时将凭据 object 传递给 AWS 服务。 Use an environment variable that is not reserved by adding the name of your app to it for example.例如,通过向其中添加您的应用程序名称来使用未保留的环境变量。

.env.local .env.local

YOUR_APP_AWS_ACCESS_KEY_ID=[your key]
YOUR_APP_AWS_SECRET_ACCESS_KEY=[your secret]

Add these env variables to your Vercel deployment settings (or Netlify, etc) and pass them in when you start up your AWS service client.将这些环境变量添加到您的 Vercel 部署设置(或 Netlify 等)中,并在您启动 AWS 服务客户端时将它们传入。

import { S3Client } from '@aws-sdk/client-s3'

...

const s3 = new S3Client({
  region: 'us-east-1',
  credentials: {
    accessKeyId: process.env.TRENDZY_AWS_ACCESS_KEY_ID ?? '',
    secretAccessKey: process.env.TRENDZY_AWS_SECRET_ACCESS_KEY ?? '',
  },
})

(note: undefined check so Typescript stays happy) (注意:未定义检查所以 Typescript 保持快乐)

If I'm not mistaken, you want to make AWS_ACCESS_KEY_ID into a runtime variable as well.如果我没记错的话,您还想将AWS_ACCESS_KEY_ID设为运行时变量。 Currently, it is a build time variable, which won't be accessible in your node application.目前,它是一个构建时间变量,无法在您的节点应用程序中访问。

// replace this 
env: {
    //..others
    AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID
  },

// with this
module.exports = {
  serverRuntimeConfig: {
    //..others
    AWS_ACCESS_KEY_ID: process.env.AWS_ACCESS_KEY_ID
  }
}

Reference: https://nextjs.org/docs/api-reference/next.config.js/environment-variables参考: https://nextjs.org/docs/api-reference/next.config.js/environment-variables

are you possibly hosting this app via vercel?您可能通过 Vercel 托管此应用程序吗? As per vercel docs, some env variables are reserved by vercel.根据 vercel 文档,一些环境变量由 vercel 保留。

https://vercel.com/docs/concepts/projects/environment-variables#reserved-environment-variables https://vercel.com/docs/concepts/projects/environment-variables#reserved-environment-variables

AWS_ACCESS_KEY_ID AWS_ACCESS_KEY_ID

AWS_SECRET_ACCESS_KEY AWS_SECRET_ACCESS_KEY

Maybe that's the reason why it is not getting those env vars也许这就是为什么它没有得到那些环境变量的原因

I was able to workaround this by adding my custom env variables into.env.local and then calling for those variables我能够通过将我的自定义环境变量添加到 .env.local 然后调用这些变量来解决这个问题

AWS.config.update({
 'region': 'us-east-1',
 'credentials': {
   'accessKeyId': process.env.MY_AWS_ACCESS_KEY,
   'secretAccessKey': process.env.MY_AWS_SECRET_KEY
 }
});

As last step would need to add these into vercel UI最后一步需要将这些添加到 Vercel UI 中

obviously not ideal solution and not recommended by AWS.显然不是理想的解决方案,AWS 也不推荐。

https://vercel.com/support/articles/how-can-i-use-aws-sdk-environment-variables-on-vercel https://vercel.com/support/articles/how-can-i-use-aws-sdk-environment-variables-on-vercel

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 aws-sdk 与@aws-sdk 之间的区别 - Difference between aws-sdk vs @aws-sdk 如何将 AWS-SDK DynamoDB 指向本地无服务器 DynamoDB - How to point AWS-SDK DynamoDB to a serverless DynamoDB local Jest - 如何模拟 aws-sdk sqs.receiveMessage 方法 - Jest - How to mock aws-sdk sqs.receiveMessage methode @aws-sdk/client-ses 和@aws-sdk/client-sesv2 有什么区别? - What is the difference between @aws-sdk/client-ses and @aws-sdk/client-sesv2? 如何在 `Node aws-sdk` sendRawEmail 函数中发送 PDF 附件? - How can send PDF attachment in `Node aws-sdk` sendRawEmail function? 如何使用 jest mock 模拟 aws-sdk,出现错误“配置中缺少区域” - How to mock aws-sdk using jest mock, getting error "Missing region in config" 如何在 nodejs 中使用 `aws-sdk` 读取 cloudwatch 日志 - How can I read cloudwatch logs using `aws-sdk`in nodejs 如何捕获在我的调用堆栈之外发生的 aws-sdk 错误? - How do I catch aws-sdk errors that occur outside of my call stack? @aws-sdk\credential-provider-node\dist-cjs\defaultProvider.js:13 CredentialsProviderError("无法从任何提供商加载凭证", false); - @aws-sdk\credential-provider-node\dist-cjs\defaultProvider.js:13 CredentialsProviderError("Could not load credentials from any providers", false); aws-sdk: NoSuchKey: 指定的密钥不存在? - aws-sdk: NoSuchKey: The specified key does not exist?
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM