如何在 NextJS 中设置 AWS-SDK 凭证 [英] How to setup AWS-SDK credentials in NextJS

查看:50
本文介绍了如何在 NextJS 中设置 AWS-SDK 凭证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 NextJs 应用程序上传一些文件到 S3.由于它是服务器端,我的印象是简单地设置环境变量应该可以工作,但事实并非如此.我知道还有其他替代方法,例如为 EC2 分配角色,但我想使用 accessKeyID 和 secretKey.

I need to upload some files to S3 from a NextJs application. 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.

这是我的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
  }
}

这是我的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()

我收到此错误:未处理的拒绝 (CredentialsError):配置中缺少凭证,如果使用 AWS_CONFIG_FILE,请设置 AWS_SDK_LOAD_CONFIG=1

I am getting this error: Unhandled Rejection (CredentialsError): Missing credentials in config, if using AWS_CONFIG_FILE, set AWS_SDK_LOAD_CONFIG=1

如果我在代码中对凭据进行硬编码,它就可以正常工作.

If I hard code the credentials in code, it works fine.

我怎样才能让它正常工作?

How can I make it work correctly?

推荐答案

您是否可能通过 vercel 托管此应用程序?根据 vercel 文档,一些 env 变量由 vercel 保留.

are you possibly hosting this app via vercel? As per vercel docs, some env variables are reserved by vercel.

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

我能够通过将我的自定义 env 变量添加到 .env.local 然后调用这些变量来解决此问题

I was able to workaround this by adding my custom env variables into .env.local and then calling for those variables

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

最后一步需要将这些添加到 vercel UI 中

As last step would need to add these into vercel UI

显然不是理想的解决方案,AWS 也不推荐.

obviously not ideal solution and not recommended by AWS.

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

这篇关于如何在 NextJS 中设置 AWS-SDK 凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆