Troubleshooting image upload issues with AWS S3 in Next.js version 13

I encountered a consistent problem with using the AWS SDK in NextJS to upload images. I keep getting error code 403 (Forbidden). Could there be other reasons why this error is occurring besides the accessKeyId and secretAccessKey being invalid? Below is my basic code implementation:

const s3 = new S3({
  accessKeyId: process.env.NEXT_PUBLIC_APP_AWS_ACCESS_KEY_ID,
  secretAccessKey: process.env.NEXT_PUBLIC_APP_AWS_SECRET_ACCESS_KEY,
  region: process.env.NEXT_PUBLIC_APP_AWS_REGION,
  signatureVersion: 'v4',
});

export const uploadObject = async (
  file: File,
  key: string,
  onProgress: (percent: number) => void,
  onSuccess: () => void,
  onError: () => void
) => {
  const params = {
    Bucket: process.env.NEXT_PUBLIC_APP_AWS_S3_BUCKET!,
    Key: key,
    Body: file,
    ContentEncoding: 'base64',
    ContentType: file.type,
  };

  s3.upload(params)
    .on('httpUploadProgress', (evt) => {
      onProgress(Math.ceil((100 * evt.loaded) / evt.total));
    })
    .send((error: any, data: any) => {
      if (error) {
        onError();
      } else {
        onSuccess();
      }
    });
};

Do you see any issues with my code?

Answer №1

When you encounter a 403 error, it means that the authorized "user" lacks the necessary permissions to perform the desired action. In your specific situation, it appears that there are missing privileges either on the bucket or within IAM.

One way to address this could be by implementing a policy similar to the following:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Effect":"Allow",
         "Action": "s3:ListAllMyBuckets",
         "Resource":"*"
      },
      {
         "Effect":"Allow",
         "Action":[
            "s3:PutObject",
            "s3:PutObjectAcl",
            "s3:GetObject",
            "s3:GetObjectAcl",
            "s3:DeleteObject"
         ],
         "Resource":"arn:aws:s3:::DOC-EXAMPLE-BUCKET1/*"
      }
   ]
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

There seems to be a compatibility issue between Angular 16 and Bootstrap 5 styling

In my angular.json, I have defined my styles in the following way: "styles": [ { "input": "node_modules/bootstrap/dist/css/bootstrap.min.css", "bundleName": "ltrCSS" }, { "input": "node_mod ...

Restrict the number of subscriptions allowed for an rxjs observable

Seeking a replacement for observable, subject, or event emitter that allows only one subscription at a time. The first subscriber should have priority to execute its subscribe function, with subsequent subscribers waiting their turn until the first unsubsc ...

Guidance on specifying a type based on an enum in Javascript

I have a list of animals in an enum that I want to use to declare specific types. For instance: enum Animals { CAT = 'cat', DOG = 'dog', } Based on this Animal enum, I wish to declare a type structure like so: type AnimalType = { ...

Include the providers after declaring the AppModule

When it comes to Angular 2+, providers are typically registered in the following manner: // Using the @NgModule decorator and its metadata @NgModule({ declarations: [...], imports: [...], providers: [<PROVIDERS GO HERE>], bootstrap: [...] }) ...

What is the process for defining a property type as a textual representation of a Type name in TypeScript?

Consider the following classes and interface: class Foo {} interface Bar {} I am looking to define a type that includes a property with a specified type: type DynamicPropertyName<T> = ... <-- ??? After defining the type, I want to use it like th ...

Leveraging typegoose in a multitenant environment within the nestjs framework

I am looking to implement multitenancy functionality where each tenant will have its own database. Can Typegoose dynamically create connections for this purpose? ...

Updating the state in React Native does not occur

I'm facing an issue where I can't seem to update the state using useState while coding in React Native. The component in question is a styled TextInput named SearchField. Can anyone help me figure out what I might be doing wrong that's preve ...

Looking to develop a dynamic password verification form control?

I am in the process of developing a material password confirmation component that can be seamlessly integrated with Angular Reactive Forms. This will allow the same component to be utilized in both Registration and Password Reset forms. If you would like ...

Navigating the enum data model alongside other data model types in Typescript: Tips and Tricks

In my different data models, I have utilized enum types. Is it possible to compare the __typename in this scenario? enum ActivtiyCardType { Dance, ReferralTransaction, } type ActivityCardData = { __typename:ActivtiyCardType, i ...

The issue with functions not executing when triggered by HammerJS

In my application, there is a component that displays information for different days as they are cycled through using the functions dayUp() and dayDown(). Here is an example of how these functions are structured: dayUp() { if (this.dayCount == 7) { ...

Introducing the cutting-edge NextJS 13 Beta App Directory API powered by Prisma

With the recent update from NextJS allowing access to API's within the APP directory, I've encountered some difficulties getting Prisma to work with it. While I can make Prisma fully functional with pages/api, I'm struggling to get it workin ...

Updating the DOM with an EventListener in Angular 5 is not functioning properly

Situation : Utilizing an Angular PWA for communication with an iOS native app via WKWebview. Implementing messageHandlers to facilitate data sharing between TypeScript and Swift logic code. Issue : Employing addEventListener to monitor a specific event on ...

The setInterval function continues executing even after the page has been changed

I'm encountering an issue with my function where it continues to run even after the page has changed, resulting in an error. How can I go about stopping this behavior? Thank you! componentDidMount() { var current = 0; var slides = document.g ...

The Next.js application refreshes when navigating to a new page

Currently, I am working with nextjs version 12.1.6, react-dom version 18.0.5, and next-auth 4.6.1 in my application. It consists of two routes - an index page and a login page. However, whenever I navigate between these two pages, the entire app rerenders. ...

Avoid including any null or undefined values within a JSON object in order to successfully utilize the Object.keys function

My JSON data structure appears as follows: { 'total_count': 6, 'incomplete_results': false, 'items': [ { 'url': 'https://api.github.com/repos/Samhot/GenIHM/issues/2', 'repository_url' ...

The attempt to deploy my NextJS app to Vercel failed, with the deployment only displaying the message "Compilation Failed."

I'm having trouble understanding why my deployment keeps crashing, as there are no significant error messages, only a bunch of warnings that it should still work (it has worked in the past with these same warnings). Here is the build log: Running bui ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

Changing the color of a selected list element using an Angular directive

I'm currently facing an issue with my directive that is supposed to turn a list element red when clicked. It works fine, but I also want it to revert back to black when another list item is selected, so only one item stays in red color. Here is how I ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

I am encountering an error stating "Cannot locate module 'nestjs/common' or its related type declarations."

I am currently working on a controller in NestJS located in the file auth.controller.ts. import { Controller } from 'nestjs/common'; @Controller() export class AppController {} However, I encountered an error that says: Error TS2307: Cannot fin ...