If you've worked with Node.js and Express, you've probably used Multer at some point to handle file uploads.
Recently, while building a blog platform using Next.js App Router, I needed to implement a feature that allowed authenticated users to publish blog posts with cover images.
My initial thought was simple:
I need an upload API, so I'll use Multer just like I do in Express.
But after exploring Next.js Route Handlers, I realized something interesting: I didn't need Multer at all.
Next.js already provides a native way to handle multipart form data.
In this article, I'll share how I approached file uploads, why I didn't use Multer, how I integrated Cloudinary, and some important things I learned along the way.
This isn't just a copy-paste implementation. I'll explain the reasoning behind the decisions too.
1. What I wanted to build
I was working on a blog platform where users could:
- Write a blog post.
- Select a category.
- Upload a cover image.
- Publish the post.
I wanted the following workflow:
- User fills in the blog form.
- Frontend sends the post details and image to the backend.
- Backend authenticates the user.
- Backend validates the input and image.
- Backend uploads the image to Cloudinary.
- Backend receives the image URL and public ID.
- Backend saves the post and image details in the database.
My tech stack:
- Next.js App Router
- TypeScript
- Prisma
- MongoDB
- Cloudinary
- Auth.js
I chose Cloudinary because I wanted image storage and delivery to be handled by a dedicated media service instead of storing uploaded files inside my application.
2. Do we need Multer in Next.js?
This was one of the first things I investigated.
If you've worked with Express, you might have written something like this:
const upload = multer({ storage: multer.memoryStorage(), }); app.post("/upload", upload.single("image"), (req, res) => { console.log(req.file); }); Multer is middleware designed to handle multipart/form-data in Express applications.
But Next.js App Router Route Handlers work differently.
They provide the Web Request API, which includes:
const formData = await request.formData(); const file = formData.get("file"); That's it. No Multer configuration, no upload middleware, and no additional multipart parser needed for this basic use case.
You can access the uploaded file directly using the native FormData API.
Important: This applies to Next.js App Router Route Handlers. If you're using the older Pages Router with API routes, the implementation is different.
3. Sending files from the frontend
The first thing I needed was to send both text fields and the image in a single request.
For that, I used the browser's native FormData API.
const handlePublish = async () => { if (!title.trim() || !content.trim() || !category || !coverImage) { alert("Please complete all fields"); return; } try { setPublishing(true); const formData = new FormData(); formData.append("title", title); formData.append("content", content); formData.append("category", category); formData.append("file", coverImage); const response = await fetch("/api/posts", { method: "POST", body: formData, }); const data = await response.json(); if (!response.ok) { throw new Error(data.message || "Failed to publish post"); } router.push("/blog"); } catch (error) { console.error(error); alert( error instanceof Error ? error.message : "Something went wrong" ); } finally { setPublishing(false); } }; A small but important detail:
Don't manually set the Content-Type header when sending FormData.
Avoid doing this:
headers: { "Content-Type": "multipart/form-data", } The browser automatically sets the correct content type, including the multipart boundary.
If you set it manually, you can end up with an invalid request because the boundary information may be missing.
4. Understanding file handling in Next.js Route Handlers
On the backend, I created:
app/ └── api/ └── posts/ └── route.ts Inside the POST handler, I could access the submitted fields like this:
const formData = await req.formData(); const title = formData.get("title"); const content = formData.get("content"); const category = formData.get("category"); const file = formData.get("file"); One thing worth understanding is that formData.get() doesn't guarantee that the returned value is a string.
It can return a string, a File, or null.
So I validated the values before using them:
if ( typeof title !== "string" || !title.trim() || typeof content !== "string" || !content.trim() || typeof category !== "string" || !category.trim() || !(file instanceof File) ) { return NextResponse.json( { message: "All fields are required" }, { status: 400 } ); } This prevents unexpected values from reaching the rest of the application.
5. Why I separated the upload logic
Initially, it was tempting to put everything inside the API route:
- Authentication
- Form parsing
- File validation
- Cloudinary configuration
- Image upload
- Database insertion
- Error handling
But that quickly makes the route difficult to maintain.
I decided to separate the upload logic into a dedicated service.
My project structure looks something like this:
src/ ├── app/ │ └── api/ │ └── posts/ │ └── route.ts ├── lib/ │ └── cloudinary.ts ├── services/ │ └── cloudinary.service.ts └── ... This way, the API route handles HTTP-related responsibilities, while the Cloudinary service handles image operations.
6. Configuring Cloudinary
First, I created a Cloudinary account and obtained the following credentials:
- Cloud name
- API key
- API secret
I stored them in my .env file:
CLOUDINARY_CLOUD_NAME=your_cloud_name CLOUDINARY_API_KEY=your_api_key CLOUDINARY_API_SECRET=your_api_secret Never expose your API secret through a NEXT_PUBLIC_ environment variable.
Then I installed the required packages:
npm install cloudinary file-type I used:
-
cloudinaryfor uploading and deleting images. -
file-typefor validating the actual file format using its binary signature.
Next, I created the Cloudinary configuration.
src/lib/cloudinary.ts
import { v2 as cloudinary } from "cloudinary"; cloudinary.config({ cloud_name: process.env.CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, }); export default cloudinary; I kept this configuration in one place so other services could reuse it.
7. Validating the uploaded image
This was an important learning point.
Initially, I thought checking file.type would be enough.
For example:
if (file.type !== "image/png") { throw new Error("Invalid image"); } But the MIME type provided by the client shouldn't be trusted on its own. A user can manipulate the request.
Instead, I used file-type to inspect the actual binary content.
I also added a file-size limit and restricted the allowed formats.
src/services/cloudinary.service.ts
import { randomUUID } from "crypto"; import cloudinary from "@/lib/cloudinary"; import { fileTypeFromBuffer } from "file-type"; const MAX_FILE_SIZE = 5 * 1024 * 1024; const ALLOWED_MIME_TYPES = [ "image/jpeg", "image/png", "image/webp", ]; interface UploadResult { secure_url: string; public_id: string; } export async function uploadImage( file: File ): Promise<UploadResult> { // Check empty file if (file.size === 0) { throw new Error("File cannot be empty"); } // Check file size if (file.size > MAX_FILE_SIZE) { throw new Error("Image must be less than 5MB"); } // Convert File into Buffer const buffer = Buffer.from(await file.arrayBuffer()); // Validate actual file type const fileType = await fileTypeFromBuffer(buffer); if ( !fileType || !ALLOWED_MIME_TYPES.includes(fileType.mime) ) { throw new Error("Invalid image format"); } // Upload image to Cloudinary return new Promise((resolve, reject) => { const stream = cloudinary.uploader.upload_stream( { folder: "my-blog/posts", public_id: randomUUID(), resource_type: "image", overwrite: false, }, (error, result) => { if (error || !result) { reject(error || new Error("Image upload failed")); return; } resolve({ secure_url: result.secure_url, public_id: result.public_id, }); } ); stream.end(buffer); }); } Let's understand a few important parts.
Why convert File into Buffer?
const buffer = Buffer.from(await file.arrayBuffer()); The native File object provides an arrayBuffer() method. Cloudinary's upload stream accepts binary data, so I converted the uploaded file into a Node.js Buffer.
Why use file-type?
const fileType = await fileTypeFromBuffer(buffer); It checks the file's binary signature rather than relying only on the MIME type sent by the browser.
This is a useful additional validation step.
Why use upload_stream?
cloudinary.uploader.upload_stream(...) Cloudinary provides an upload stream API that allows us to send the Buffer directly without first saving the file to the local filesystem.
8. Saving the image URL and public ID in the database
After a successful upload, Cloudinary returns two important values:
{ secure_url: "...", public_id: "my-blog/posts/..." } I decided to store both values in my database.
Why both?
-
secure_url: Used to display the image in the application. -
public_id: Used to identify the image when updating or deleting it from Cloudinary.
For my Prisma Post model, I added:
model Post { id String @id @default(cuid()) @map("_id") title String slug String @unique desc String img String imgPublicId String? // Other fields... } The imgPublicId field stores the Cloudinary public ID.
After adding the field, I synchronized my Prisma schema:
npx prisma db push npx prisma generate The exact database synchronization workflow can differ depending on your Prisma version and database setup.
9. Putting everything together in the API route
Now comes the interesting part.
My API route doesn't need to know how Cloudinary uploads images internally.
It just calls the upload service and uses the returned values.
app/api/posts/route.ts
import { auth } from "@/auth"; import cloudinary from "@/lib/cloudinary"; import { prisma } from "@/lib/prisma"; import { uploadImage } from "@/services/cloudinary.service"; import { NextResponse } from "next/server"; import { generateSlug } from "@/lib/utils"; export const runtime = "nodejs"; export const POST = auth(async (req) => { let uploadedPublicId: string | undefined; try { // Authentication const userEmail = req.auth?.user?.email; if (!userEmail) { return NextResponse.json( { message: "Not authenticated" }, { status: 401 } ); } // Get form data const formData = await req.formData(); const title = formData.get("title"); const content = formData.get("content"); const category = formData.get("category"); const file = formData.get("file"); // Validate fields if ( typeof title !== "string" || !title.trim() || typeof content !== "string" || !content.trim() || typeof category !== "string" || !category.trim() || !(file instanceof File) ) { return NextResponse.json( { message: "All fields are required" }, { status: 400 } ); } // Verify category const existingCategory = await prisma.category.findUnique({ where: { slug: category }, select: { slug: true }, }); if (!existingCategory) { return NextResponse.json( { message: "Invalid category" }, { status: 400 } ); } // Upload image const image = await uploadImage(file); uploadedPublicId = image.public_id; // Create post const post = await prisma.post.create({ data: { title: "title.trim()," desc: content.trim(), categorySlug: category, userEmail, slug: generateSlug(title), img: image.secure_url, imgPublicId: image.public_id, }, }); return NextResponse.json( { message: "Post published successfully", post, }, { status: 201 } ); } catch (error) { console.error("Publish post error:", error); // Remove uploaded image if database operation fails if (uploadedPublicId) { try { await cloudinary.uploader.destroy(uploadedPublicId, { resource_type: "image", }); } catch (cleanupError) { console.error( "Cloudinary cleanup failed:", cleanupError ); } } return NextResponse.json( { message: "Failed to publish post" }, { status: 500 } ); } }); I am deleting image inside catch block, Why?
Suppose the image uploads successfully, but the database operation fails. In that case, the image would remain in Cloudinary without an associated post.
To avoid leaving that orphaned image behind, I delete it in the catch block.
This is a compensating cleanup operation. It isn't a true transaction across Cloudinary and MongoDB, but it handles the common failure scenario.
For a larger production system, I'd also consider logging failed cleanup operations and retrying them asynchronously.
10. Deleting an image from Cloudinary
Since I store the public ID, deleting an image is straightforward.
I added a reusable function:
export async function deleteImage(publicId: string) { return cloudinary.uploader.destroy(publicId, { resource_type: "image", }); } This can be used when:
- A user deletes a blog post.
- A user replaces an existing cover image.
- An administrator removes inappropriate content.
However, there's an important detail: verify that the user owns the post or has the required permission before deleting its image. Never accept an arbitrary Cloudinary public ID from the client and delete it without authorization.
Also, think carefully about operation ordering. If you're replacing an image, upload the new image first, update the database, and then remove the old image. That way, a failed replacement doesn't immediately destroy the existing cover image.
11. A few things I'd consider before using this in production
The implementation above works well for my current use case: uploading one blog cover image with a maximum size of 5 MB.
But there are some additional considerations worth knowing.
1. Request body limits
Checking file.size is useful, but request.formData() has already parsed the incoming multipart request by that point.
So don't rely only on application-level file-size validation. Configure request/body-size limits at your hosting or infrastructure level too.
2. Memory usage
This approach reads the file into memory using arrayBuffer() and then creates a Buffer.
For small images, that's reasonable. For large files or high-volume uploads, consider signed direct uploads to Cloudinary so the browser uploads directly to Cloudinary instead of sending the entire file through your backend.
3. Error handling
In a larger application, I'd use custom error classes or a centralized error handler instead of returning every failure as a generic 500 response.
4. Image optimization
Cloudinary supports image transformations and delivery optimizations. You don't necessarily need to store multiple image sizes yourself.
5. Database and Cloudinary consistency
Cloudinary and your database don't share a transaction. If one operation succeeds and the other fails, you need a cleanup or retry strategy.
12. Final thoughts
One of the things I like about learning a new framework is discovering that some things I used to do manually are already handled by the framework.
Coming from Express, I initially expected to need Multer for file uploads. But Next.js App Router's native request.formData() API was enough for my use case.
The biggest learning for me wasn't just uploading an image to Cloudinary. It was understanding how to structure the implementation:
- Keep the API route focused on HTTP concerns.
- Separate file upload logic into a reusable service.
- Validate actual file content instead of trusting client-provided MIME types.
- Store both the image URL and public ID.
- Handle failures between external storage and the database.
For a small blog application, this approach is simple and practical. As the application grows, the upload strategy can evolve toward signed direct uploads and background cleanup.
If you're also learning file uploads in Next.js, I hope this saves you some time!
Source Code
Want to explore the complete implementation?
I've shared the code in my GitHub repository so you can check how I integrated file uploads with Next.js App Router and Cloudinary.
GitHub Repository: Link
Feel free to explore the code, try it in your own project, and share your feedback or suggestions.
If you find it useful, a ⭐ on the repository would be appreciated!
Have you used Cloudinary with Next.js, or do you prefer AWS S3 or another storage solution? I'd love to hear how you're handling file uploads in your projects.
