3

When I am trying to upload a file using aws-sdk-s3-client in nodejs. It throwing an validation error:

Error: Resolved credential object is not valid at SignatureV4.validateResolvedCredentials (/api/node_modules/@aws-sdk/signature-v4/dist-cjs/SignatureV4.js:163:19) at SignatureV4.signRequest (/api/node_modules/@aws-sdk/signature-v4/dist-cjs/SignatureV4.js:88:14)

Here is how my s3Client configuration file look a like:

s3_util.js

const dotenv = require("dotenv");
dotenv.config();
const AWS = require("@aws-sdk/client-s3");

const bucketRegion = process.env.BUCKET_REGION;
const accessKey = process.env.ACCESS_KEY;
const secretAccesskey = process.env.SECRET_ACCESS_KEY;

const s3 = new AWS.S3Client({
  credentials: {
    accessKeyId: accessKey,
    accessKey: secretAccesskey,
  },
  region: bucketRegion,
});

module.exports = s3;

uploading file to s3

const { PutObjectCommand, GetObjectCommand } = require("@aws-sdk/client-s3");
const s3 = require("./s3_util");
const { getSignedUrl } = require("@aws-sdk/s3-request-presigner");

const uploadFileToS3 = async (bucketName, file, uploadPath) => {
  console.log(file, "file");
  const commandProps = {
    Bucket: bucketName,
    Key: uploadPath + file.originalname,
    Body: file.buffer,
    ContentType: file.mimetype,
  };

  const uploadFileCommand = new PutObjectCommand(commandProps);
  let data;
  try {
    data = await s3.send(uploadFileCommand);
  } catch (error) {
    console.log(error);
    // const { requestId, cfId, extendedRequestId } = error.$$metadata;
    // console.log({ requestId, cfId, extendedRequestId });
  }
  return data;
};

I want the solution why it is throwing an error and what are the setps invlolved in resolving that error.

Vivek
  • 31
  • 2

2 Answers2

3

Make sure your importing dotenv module

import * as dotenv from 'dotenv'; 
dotenv.config();
const s3Client = new S3Client({
  endpoint: 'https://sgp1.digitaloceanspaces.com',
  forcePathStyle: false,
  region: 'sgp1',
  credentials: {
    accessKeyId: process.env.YOUR_ACCESS_KEY,
    secretAccessKey: process.env.YOUR_SECRET_KEY,
  }
});

this is a simple code snap since i was using digital ocean bucket it looks like this and its working.

Tanjin Alam
  • 1,728
  • 13
  • 15
0

For anyone search for this because they're having trouble with Next.'s app router, here's a solution.

My s3Client.ts file wasn't seeing the .env data, but Next.js doesn't need dotenv. So I just had to set the file that calls s3Client as "use server" (not the s3Client file itself), and it worked for me.