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

Inheritance of Generic Types in TypeScript

Could someone assist me in understanding what is incorrect with the code snippet provided here? I am still learning Typescript. interface ICalcValue { readonly IsNumber: boolean; readonly IsString: boolean; } interface ICalcValue<T> ex ...

When deploying MERN with NEXTJS, the static images from the backend fail to load. The frontend is accessing its own URL instead of the backend URL. What steps can I take to resolve this issue?

Here’s an issue from the Feature page that is causing some trouble. Everything works well when it’s run locally, but on deployment, things seem to be going haywire. While all the products load just fine, the images do not appear. Upon checking the netw ...

What is the best way to create an array of strings that can include multiple elements from a set of strings?

Exploring different roles for authorization: ['admin', 'manager', 'user'] Is there a way to create a specific type, named Roles, which is essentially a string array ( string[] ) that is limited to only containing values from ...

Click on the button to open the generated link in a new tab

How can I efficiently open a URL in a new tab after making an API call with the click of a button? Currently, the button triggers the API call and generates the URL. <button (click)="getUrl()">Connect</button> In TypeScript: getUrl() ...

Encountered an issue with retrieving schema during self-referencing validation with openapi generator

I created an openapi specification and now I am looking to generate a client for it. openapi.yaml After some research, I decided to use the openapi generator to create a typescript-axios client. This is the command I used: openapi-generator-cli generate ...

Getting URL parameters in NextJS when using Custom Document can be achieved by accessing the `ctx`

Currently, I am utilizing NextJS for generating SSR pages that are language-specific. I want to specify the lang property to indicate the language of the text. Here's what I have done so far: import Document, { Html, Head, Main, NextScript } from &qu ...

Ensure that child components' property types are enforced in TypeScript

I am trying to enforce the type of a property in a child component. I expected the code below not to compile because Child's property name is not correctly typed inside Parent within the app. However, there is no compiler warning displayed. Is there ...

Higher-Order Component integrated with HTMLElement

Check out this complex code snippet I created: export type AdvancedHoverElementProps<TElement extends HTMLElement> = React.HTMLProps<TElement> & { hoverDuration: number, onHoverChanged: (isHovering: boolean) => void }; export ...

Facing a challenge with client-side errors upon deploying Next.js to Vercel, unfortunately, the logs aren't offering any helpful clues

After successfully deploying my NextJs application to Vercel, I encountered an issue. While the application runs perfectly when tested locally, I faced an error message upon opening it in the browser on Vercel. The browser console provided a link to the Re ...

The type 'xxxx' is not compatible with the parameter type 'JSXElementConstructor<never>'

I am currently enrolled in a TypeScript course on Udemy. If you're interested, you can check it out here. import { connect } from 'react-redux'; import { Todo, fetchTodos } from '../actions'; import { StoreState } from '../red ...

Is there a way to delete the component <Header /> within the _app.tsx file on a single page?

In the _app.tsx file, I have a component that is rendered on all pages. However, I want to exclude this component from the payment.tsx page. Is there a way to achieve this? ...

What's the best way to test a TSX file importing SCSS using Jest?

Here is my configuration for jest: module.exports = { roots: ['<rootDir>/src'], collectCoverageFrom: [ '<rootDir>/src/**/*.{ts,tsx}' ], coverageDirectory: 'coverage', testEnvironment: 'jsdom&apo ...

The collapsible tree nodes overlap one another in the D3.js visualization

I'm currently working on integrating a d3 code into Power BI for creating a collapsible tree structure. Each node in the tree is represented by a rectangular box, but I've run into an issue where nodes overlap when their size is large. Below is t ...

Submit a pdf file created with html2pdf to an S3 bucket using form data

Currently, I have the following script: exportPDF(id) { const options = { filename: 'INV' + id + '.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, dpi: 300, letterRendering: true, useC ...

Exploring the TypeScript Type System: Challenges with Arrays Generated and Constant Assertions

I am currently grappling with a core comprehension issue regarding TypeScript, which is highlighted in the code snippet below. I am seeking clarification on why a generated array does not function as expected and if there is a potential solution to this pr ...

Why is the `node-config` configuration undefined within a TypeScript Jest environment?

I have a TypeScript module that is functional in both development and production environments. It utilizes https://github.com/lorenwest/node-config. When I attempt to import it into Jest for testing purposes, I encounter an error suggesting that the config ...

Utilizing ES2020 functionalities within a Next.js application: A step-by-step guide

Recently, I've been experimenting with utilizing the optional chaining feature in ES2020 within my next.js project. However, it seems that a new loader is required for this functionality. Can anyone offer some guidance on how to address this issue? ...

What prevents TypeScript from automatically inferring tuple return types in RxJs streams?

When composing an observable stream, the map function infer is a union instead of a tuple. For instance: import { Component } from '@angular/core'; import { from } from 'rxjs'; import { map, tap } from 'rxjs/operators'; expo ...

Managing cookies in Next JS 14 for authentication using Django framework

After struggling to get things working, I am enjoying the combination of Next.js 14 with Django as my backend. Now, the challenge I face is authenticating users. Currently, I have a client form with a function handler that triggers a server action. While I ...

Maintaining checkbox selection while switching pages in Angular

When I try to edit the settings for accepting payments in all currencies under the "Pricing" component, the checkbox is unchecked every time I return to the "General" section. How can I prevent this from happening and keep the checkbox checked? Refer to ...