← Back to list

Upload files with NextJS + Fetch + Api routes + Typescript

You will learn, how to upload files using React, NextJs and Fetch API.

Igor Gaponov in Towards Dev · 2022-04-22 07:52 · 84 claps · 1.4 min read
#react #nextjs #typescript #fetch-api #upload
Open on Medium ↗
Wiki topics: 🌐 · Web Development

Upload files with NextJS + Fetch + Api routes + Typescript

You will learn, how to upload files using React, NextJs and Fetch API.

First of all, let’s create NextJs application by running:

yarn create next-app --typescript

After the installation is complete, run yarn dev to start the development server on [http://localhost:3000](http://localhost:3000) .

If you open the page, you will see something similar to the following:

Now let’s install the packages, which will help us to parse form data:

yarn add -D formidable @types/formidable

Creating the form

We will create small form, where we can upload files. I will simplify the code to make it more clear.

Go to pages/index.js and replace all the default code with the following:

[embed]

Here we are using multiple files uploading. If you want to upload only one file, remove multiple from input:file :

<input type="file" name="myfile" ref={inputFileRef} />

API Route

Let’s create an endpoint, where we will process the uploaded files.

Create the filepages/api/upload.ts :

[embed]

Congratulations, we’re done! You can test your form!

All files will be saved in directory /uploads inside your project root.

Use Api route as proxy

Here I suggest you to assume, that we need to transfer our files somewhere else to another server, because we don’t want to store them and doing difficult operations on files.

Add some new packages:

yarn add -D form-data node-fetch

Change you /pages/api/upload.ts to:

[embed]

Don’t forget to replace PATH_TO_ANOTHER_SERVER .

This is it, enjoy! Full repo https://github.com/gapon2401/upload-files-nextjs

Feel free to subscribe, clap and share the article with anyone you’d like. Here you can find all my articles. Thanks, I appreciate your support!


메타데이터
post_id
8150f9fa2332
slug
upload-files-with-nextjs-fetch-api-routes-typescript-8150f9fa2332
url
https://towardsdev.com/upload-files-with-nextjs-fetch-api-routes-typescript-8150f9fa2332
canonical_url
https://towardsdev.com/upload-files-with-nextjs-fetch-api-routes-typescript-8150f9fa2332
author_url
https://medium.com/@igaponov
status
ok
fetched_at
2026-07-27 05:39:41