Nextjs Server Actions File Upload from Scratch to Deployment

Author

Reads 606

Closeup of switch in server with connectors and adapters connected to plastic device in dark room on blurred background inside
Credit: pexels.com, Closeup of switch in server with connectors and adapters connected to plastic device in dark room on blurred background inside

In Next.js, server actions can be used to handle file uploads efficiently. A server action is a function that runs on the server-side, allowing for more control over the file upload process.

To create a server action for file upload, you'll need to create a new file in your Next.js project, specifically in the `pages/api` directory. This is where you'll write the code for your server action.

The server action file will need to import the `NextApiRequest` and `NextApiResponse` types from the `next` module. These types will help you define the structure of your API request and response.

You can then use the `multer` middleware to handle multipart/form-data requests, which is the format used for file uploads. In the example, `multer` is used to store the uploaded file in the `/tmp` directory.

Setting Up Next.js App

To set up a Next.js app, start by creating a new project with the command `npx create-next-app@latest --typescript file_uploader`. This will create a new Next.js project with Typescript support.

Next, navigate to the project directory and open it in your favorite code editor. For example, you can run `code file_uploader` to open it in Visual Studio Code.

Project Setup

Credit: youtube.com, How I Setup My NextJs Projects From Scratch

To set up our Next.js app, we'll start by running a command in the terminal to create a new project. Open your terminal and type in `npx create-next-app@latest --typescript file_uploader`.

We'll use the `typescript` flag to create a Next.js project with TypeScript support instead of JavaScript. This will give us more flexibility and better code organization.

In the terminal, navigate to where you keep your projects and run the command. After the command is completed, open the project in your favorite code editor.

Because we're using Tailwind CSS, we don't need the CSS modules file at `styles/Home.module.css`, so feel free to delete it. This will declutter our project and make it easier to work with.

Next, we'll create the upload API file at `pages/api/upload.ts`. We can do this by creating a new file or renaming the existing `api/hello.ts` file to `api/upload.ts`. Either way, we'll have a simple upload endpoint that returns a string.

Credit: youtube.com, Next JS Project: Setup and First Steps

To verify that everything is working as expected, start the server using `npm run dev` and wait for it to successfully start. Then, open a new tab and visit `http://localhost:3000` to see the homepage with a simple title, file input, and footer.

We can test the API endpoint by visiting `http://localhost:3000/api/upload`, and we should see the response from the server. However, we'll need to fix the API to only accept POST requests, not GET requests.

Create App AI

CreateAppAI is a powerful tool that helps you set up your Next.js app with ease. It auto-generates a Profile route with file upload capabilities.

This means you can quickly create a profile page that allows users to upload files, which is super convenient for many use cases.

Creating an Upload API

To create an Upload API in Next.js, you'll need to set up a server to manage file uploads. This process can be quite time-consuming and prone to errors, particularly for developers who are aiming to create efficient and reliable applications.

Credit: youtube.com, Uploading files in NextJs 13 using Server Actions

You can start by creating a file called api/uploadthing/core.ts in your app folder and add the following code to define a file router for handling file uploads. This router will act as a blueprint for handling uploads, defining what can be uploaded, where it goes, and what happens after the upload is finished.

The code snippet above defines a file router for handling product image uploads in a Next.js application using UploadThing. You named the route configuration productImage because you are only handling images.

To create a Next.js API route using FileRouter, create a file called api/uploadthing/route.ts in your app folder and add the following code. This route serves as the entry point for receiving file uploads from the client/frontend.

You can also use the UploadThing component to upload images. In your app/pages.tsx file, import the UploadDropzone component from the utils folder and copy and paste the following code. The endpoint prop expects a string value that matches a key in the ourFileRouter object, which specifies the precise file route configuration.

When creating the FileRoute endpoint, you can specify file types and set a maximum file size limit. You can also provide optional middleware for additional logic before or after uploading. This ensures type safety through type assertions and type aliases.

Credit: youtube.com, Use Server Actions to Upload Files in Next.js with Cloudinary - Dev Hints

To achieve this, add the following code to the ourFileRouter object, beneath productImage, in your app/api/uploadthing/core.ts file. This code snippet creates a file route for product PDFs and other supported file types.

You can also use the useUploadThing Hook to handle file uploads inside the CustomForm function. The hook takes two arguments: an endpoint, productImage, that you described earlier, and a callback function that gets called when the upload finishes successfully on the client side.

The useForm Hook from react-hook-form handles the form state and connects easily with Zod via the zodResolver to execute formSchema validation. This ensures that the form data is validated before being sent to the server for file upload.

In your api/upload.ts endpoint, you can use the formidable package to save the uploaded file to a state. After saving the file, you can send the path to that file back to the client-side as a response.

You can also handle multiple file uploads by reusing some design and logic from your SingleFileUploadForm component. You can remove the Upload file button and instead, upload the files as soon as they are chosen.

Credit: youtube.com, Uploading Files With Next.js 14 Using Server Actions with Strapi 5

When sending multiple files to the server, you can use the onFilesUploadChange event handler to get the selected files, validate them, and then post them to your api/upload.ts endpoint. After getting a successful response from your API, you can convert your selected images with URL.createObjectURL in order to preview them.

Finally, you can define the form schema using Zod to specify the intended structure and data types of the form data. This schema is straightforward and uses any() in the file field to demonstrate file upload functionality without complicating validation logic.

You can also handle form submission by extracting the uploaded files from the form data, converting the file field to an array, triggering the upload process using the useUploadThing Hook, and returning the result.

To send a file to the server, you can use the Fetch API and create a new instance of FormData. You can append the file to the FormData with the key media, and then send a post request with the FormData to your API.

When the file upload API returns JSON, you can use await res.json() to get the response data. You can then handle exceptions and errors if there were any, and finally, you can preview the uploaded files using URL.createObjectURL.

Rosemary Boyer

Writer

Rosemary Boyer is a skilled writer with a passion for crafting engaging and informative content. With a focus on technical and educational topics, she has established herself as a reliable voice in the industry. Her writing has been featured in a variety of publications, covering subjects such as CSS Precedence, where she breaks down complex concepts into clear and concise language.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.