March 30, 2022

Fullstack App With TypeScript, PostgreSQL, Next.js, Prisma & GraphQL: Image upload

This article is the fourth part of the course where you build a fullstack app with Next.js, GraphQL, TypeScript, Prisma and PostgreSQL. In this article, you will learn how to add image upload using AWS S3.

Fullstack App With TypeScript, PostgreSQL, Next.js, Prisma & GraphQL: Image upload

Table of Contents

Introduction

In this course you will learn how to build "awesome-links", a fullstack app where users can browse through a list of curated links and bookmark their favorite ones.

In part 3, you added authentication to the app and created a page for adding new links using placeholder images.

This guide will teach you how to add support for image upload using AWS S3. If you're following along from part 3, you can skip project setup and jump into the using AWS S3 to add support for image upload section.

Note: The example code used for part 4 differs slightly by including functionality such as bookmarking favorite links. Feel free to refer to the part 4 branch to update your current application to match what is used in this tutorial.

Development environment

To follow along with this tutorial, ensure you have Node.js and the GraphQL extension installed. You will also need a PostgreSQL database running.

Note: you can set up PostgreSQL locally or a hosted instance on Heroku. Note that you will need a remote database for the deployment step at the end of the course.

Clone the repository

You can find the complete source code for the course on GitHub.

Note: Each article has a corresponding branch. This way, you can follow along as you go through it. By checking out the part-4 branch, you have the same starting point as this article. There might be a few differences between each branch, so to not run into any issues, it is recommended that you clone the branch for this part

To get started, navigate into the directory of your choice and run the following command to clone the repository:

Navigate into the cloned application and install the dependencies:

Seeding the database

After setting up a PostgreSQL database, rename the env.example file to .env and set the connection string for your database. After that, run the following command to create the tables in your database:

If prisma migrate dev did not trigger the seed step, run the following command to seed the database:

Refer to Part 1 – Add Prisma to your Project for more details on the format of the connection string.

This command will run the seed.ts file in the /prisma directory. seed.ts creates four links and one user in your database using Prisma Client.

Note: Refer to part 3 for how to set up Auth0.

Project structure and dependencies

You will see the following folder structure:

This is a Next.js application that uses the following libraries and tools:

The pages directory contains the following files:

  • index.tsx: page that displays all links in the app. Supports pagination
  • link/[id].tsx: page that displays an individual link and allows users to bookmark it.
  • admin.tsx: admin page that requires the logged in user to have the ADMIN role. This page allows admins to create new links.
  • favorites.tsx: page that shows a user's bookmarked links.
  • _app.tsx: global app component. Allows you to persist layout between page changes and keeping state when navigating pages.
  • api/graphql.ts: GraphQL endpoint using Next.js's API routes.
  • api/auth/[...auth0].ts: dynamic API route Auth0 creates to handle authentication.
  • api/auth/hook.ts: API route that handles creating a user record in the database.

Using AWS S3 to add support for image upload

In the application's current state, an admin can create a link. However, the admin cannot attach an image to the created link. This guide will teach you how you can leverage AWS S3 – an object storage service – to upload images.

Note: To continue with the tutorial, you need an AWS account. You can create an account here. AWS will require you to provide a credit card to complete the signup. AWS provides a free tier that will allow you to explore different AWS services – including S3 – for free.

Create an Identity Access Management user

To interact with AWS resources, you have to create an Identity Access Management (IAM) user with the proper permissions. The IAM user will allow you to interact with resources on AWS programmatically.

To do that, select Security Credentials from the dropdown menu located in the top right corner of the page – where your username is.

AWS S3

Next, select the Users option from the Access Management dropdown located in the left sidebar.

AWS S3

Next, click the Add users button to create a new user.

AWS S3

Provide a recognizable username for the newly created user and check the Access key - programmatic access checkbox.

AWS S3

Next, you need to specify what the user can do with different AWS resources by setting permissions. Select the Attach existing policies directly option and type "S3" in the search filter. Select AmazonS3FullAccess.

AWS S3

You can optionally define tags for newly created IAM users, but you do not need to do that for this project, so click Next: Review.

AWS S3

After reviewing that the user has the correct permissions and username, click Create user.

AWS S3

Finally, copy the "Access Key ID" and the "Secret Access Key" and store them in your .env file

AWS S3

Note: These credentials can only be viewed once, so in case you lose these credentials or want to change them, you will need to generate new ones.

Create and configure a new S3 bucket

The next step is to create an AWS S3 bucket which will store the uploaded objects. You can find the S3 service by looking it up in the search bar or by going to https://s3.console.aws.amazon.com/.

AWS S3

Note: there are different ways you can provison resources in AWS, you are using the AWS console for simplicity

Next, click on Create bucket to create a new bucket. AWS S3

Pick a name and a region for your bucket. Save these values in your .env file.

Note: The bucket name has to be unique and must not contain any spaces or uppercase letters.

Go ahead and create the bucket by navigating to the bottom of the page and clicking the Create bucket button. You can stick with the defaults settings for now, but you'll update them in the following steps.

AWS S3

Once S3 has provisioned the Bucket, navigate to it by selecting it in the table.

Navigate to the Permissions tab and click on the Edit button in the Block public access (bucket settings) section. AWS S3

Uncheck Block all public access and click on Save changes. You need to allow public access because your application needs to access the images uploaded on AWS S3.

AWS S3

Next, update the resource policy to grant the application access to the Bucket and its contents. In the Permissions of your S3 Bucket, navigate to the Bucket policy section. Select Edit and add the following while changing "name-of-your-bucket" placeholder to the name of your Bucket:

AWS S3

Next, you need to allow your application, which will be on a different domain, to access the stored images. In the Permissions tab of your bucket, scroll to the Cross-origin Resource Sharing (CORS) section at the bottom and add the following to it:

AWS S3

Note: Before deploying your application, ensure you update the "AllowedOrigins" array with the URL pointing to your application.

Add image upload functionality to your application

Now that you've set up S3, the next step is adding image upload functionality to your application. You'll create an API endpoint and update the frontend to handle image upload.

First, install the aws-sdk package by running the following command:

Next, create a new file called upload-image.ts located in the pages/api/ directory and add the following code to it:

  1. Creates a new instance of the S3 Bucket
  2. Updates the main configuration class with the region, credentials, and additional request options
  3. Generates a presigned URL allowing you to write to the S3 Bucket
  4. Return the presigned URL that will be used for file upload

Finally, update the pages/admin.tsx file with the following code:

The form includes a new input field to handle file upload. The input field accepts images of either .png or .jpeg formats. Whenever an image is uploaded, the uploadPhoto function sends a request to the /api/upload-image API endpoint. A toast will be shown as the request is being resolved by the API – success, loading, or error states.

When the form is submitted, the URL of the image is included as a variable in the createLink mutation. A toast will appear as the mutation is being executed.

Summary and next steps

You learned how to add support for image upload using AWS S3. In the next part, you will deploy your app to Vercel and learn how you can use the Prisma Data Proxy to manage your database connection pool to ensure your application doesn't run out of connections.

Don’t miss the next post!

Sign up for the Prisma Newsletter