The server-side image compression feature in Next.js 15 is a game changer for those who work with many images. Here are a few standout features:
Performance: Compressing images on the server can significantly improve loading times. Users typically appreciate faster loading pages, and search engines reward these efforts with better rankings.
Quality Control: With sharp, you can adjust the quality and format of your images. It supports multiple formats like JPEG, PNG, and WebP, allowing you to choose the best fit for your needs.
Automatic Resizing: Whether your images are too large or too small, server actions allow you to automatically resize them during upload. This keeps your application responsive and looking great on different devices.
Create a Next.js app: Open your terminal and run
npx create-next-app@latest my-next-app
Create FormUser.jsx component
"use client";
import React, { useState } from "react";
import Image from "next/image";
import { editUserProfile } from "@/src/utils/actions";
import { FaRegUser } from "react-icons/fa6";
import { FaRegEdit } from "react-icons/fa";
import { useActionState } from "react";
import imageCompression from "browser-image-compression";
const UpdateUser = ({ user }) => {
const [action, isPending] = useActionState(editUserProfile,undefined);
const [dataUrl, setDataUrl] = useState(user?.imageUrl);
const [formData, setFormData] = useState({
name: user.name || "",
job: user.job || "",
});
const handelChange = (key: string, value: string) => {
setFormData((prv) => { return { ...prv, [key]: value };})};
const readURL = async (event: React.ChangeEvent<HTMLInputElement>) => {
const input = event.target;
if (input.files && input.files[0]) {
const file = input.files[0];
const options = {
maxSizeMB: 1,
maxWidthOrHeight: 800,
useWebWorker: true,
};
try {
const compressedFile = await imageCompression(file, options);
const reader = new FileReader();
reader.onload = () => {
const src = reader.result;
if (src) {
setDataUrl(src as string);
}
}; reader.readAsDataURL(compressedFile);
} catch (error) {console.log("Error while compressing the image", error)
} }
}; return (
<div className="w-full">
<form action={action} className="">
<div className="">
<Image className=""
src={dataUrl} width={300} height={300} alt="user image"/>
<label className="text-base text-gray-500 font-semibold mb-2 block"> Upload Image</label>
<input type="file" onChange={readURL} accept="image/*" readOnly
className=""/>
</div>
<div />
<div className="">
<input name="id" value={user._id} hidden readOnly />
<input type="text" name="imageUrl" value={dataUrl} hidden readOnly />
<div className="relative w-full">
<FaRegUser className="absolute left-3" />
<input className="w-full border-2 rounded-lg font-mono bg-gray-100
placeholder:capitalize px-12 py-1.5 outline-mainColor"
type="text" placeholder="new name" name="name"
value={formData.name}
onChange={(e) => handelChange(e.target.name, e.target.value)}/></div>
<div className="mx-auto w-4/5 flex flex-col justify-center items-center"/>
<button type="submit" disabled={isPending}
className="rounded-lg flex">
<FaRegEdit className="w-5 h-5" />
<span className="font-bold"> {isPending ? "updating..." : "Update"}</span></button>
</form>
</div>
)};
export default UpdateUser;
Install browser-image-compression
npm i browser-image-compression
Create addUser.js as a server function
1.create action.js file in app directory
"use server";
import connect from"./mongo";
import User from"./User";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
export const addUser=async (formData) => {
const { id, name, email, imageUrl } =Object.fromEntries(formData);
try {
connect();
const newUser=newUser({
id,
name,
email,
imageUrl,
});
await newUser.save();
} catch (error) {
console.log(error);
}
revalidatePath("/");
redirect("/success");
};
Create success page in app directory
1. inside folder create page.jsx
import React from "react";const page = () => { return ( <div className="w-screen h-screen"> <div className="bg-green-200 border-green-600 text-green-600 border-l-4 p-4" role="alert" > <p className="font-bold">Success</p> <p>Congratulations, you are creating user successfully.</p> </div> </div> );};export default page;
Create mongo.js file
1.install MongoDB & mongoose
npm i mongoose && npm i mongodb
2.create connect function
import mongoose from "mongoose";
const connect=async () => {
try {
await mongoose.connect(process.env.MONGO);
console.log("connect good");
} catch (err) {
throw new Error("connection failed !");
}
};
export default connect;
create User.js modal for mongoDb collection
import mongoose from "mongoose";
const { Schema } =mongoose;
const userSchema=newSchema(
{
name: {
type:String,
unique:true,
required:true,
min:3,
max:20,
},
email: {
type:String,
unique:true,
required:true,
match: /.+\@.+\..+/,
},
imageUrl: {
type:String,
required:false,
},
job: {
type:String,
required:false,
},
},
{ timestamps:true }
);
const User=mongoose.models?.users||mongoose.model("users", userSchema);
export default User;
Conclusion
By integrating server-side image upload and compression in Next.js 15, you can significantly enhance your application's performance and user experience. This guide has provided all the necessary steps to set up and optimize the process effectively.
If you want to read more information about how to boost traffic on your Website just visit -->other videos