
Before we dive in, why not take a quick peek at my portfolio: https://priyalraj.com, & while you’re at it, check out my SaaS venture: https://shavelinks.com, it’s where innovation meets simplicity.
Have you ever opened a web app and thought it was too slow? Sometimes it’s not the code — it’s the size of the data we send to the client from the server. The bigger the response, the longer it takes to reach the user.
That’s where gzip comes in. It’s a simple, powerful tool to shrink your API responses. Smaller responses = Faster apps = Happier users.
So, in this article, I’ll show you how to use the built-in zlib module in Node.js to gzip your API responses in a Next.js app. We’ll also review when it’s worth using, some pros and cons, real performance benchmarks, and common mistakes to avoid.
zlib.gzip() — no extra libraries needed.zlib.createGzip() to avoid memory overhead.Gzip is a way to compress data so it travels faster over the internet. It’s like zipping up a file — smaller size, same content.
When your server sends a gzipped response, the browser automatically unzips it. This makes your APIs faster and uses less bandwidth.
In Node.js, gzip is available out of the box via the zlib module. No extra setup needed.
You should use gzip compression when you’re sending large chunks of text-based content, like:
It’s best for payloads over 1 KB — compressing smaller stuff can make them bigger (weird, right?). For optimal performance, it’s recommended to test and profile with different sizes to determine the most efficient setting.
Let’s say you have an API endpoint /api/data that sends a big JSON object. Here’s the compressed version using zlib's gzip method:
import { NextResponse, NextRequest } from 'next/server';
import { gzip } from 'zlib';
import { promisify } from 'util';
const gzipAsync = promisify(gzip);
export async function GET(request: NextRequest) {
try {
const data = {
message: 'Here`s a large JSON response from your API!',
list: Array(5000).fill('🧠'),
};
const json = JSON.stringify(data);
const uncompressedSize = Buffer.byteLength(json, 'utf-8');
const compressed = await gzipAsync(json);
const compressedSize = compressed.length;
console.log(`Uncompressed Size: ${uncompressedSize} bytes`);
console.log(`Compressed Size: ${compressedSize} bytes`);
return new NextResponse(compressed, {
status: 200,
headers: {
'Content-Type': 'application/json',
'Content-Encoding': 'gzip',
'Cache-Control': 'no-store',
},
});
} catch (error: unknown) {
console.error("Error", error);
return NextResponse.json({ data: [], message: "Please contact admin.", status: 500 });
}
}That’s it — Next.js will send a gzipped version of your response, and the browser will automatically unzip it.
Here’s a simple test I ran using the above Next.js API code:
As you can see, gzip adds a bit of CPU time but reduces the response size dramatically. That trade-off is worth it, especially for users on slower networks or mobile data, and for reducing your server’s bandwidth usage too.
Like everything in development, gzip comes with its benefits and trade-offs. Let’s break down the good and the not-so-good sides of using gzip.
Content-Encoding: gzip in the headers, otherwise the browser won’t unzip it, and you will see some alien code.Some devs get nervous about HTTP compression because of an attack called BREACH. It’s a way attackers can use response size differences to guess secure tokens.
This mostly affects sensitive GET responses that include secret data (like CSRF tokens). What to do:
Adding gzip to your API routes is one of those easy wins that instantly makes your app feel snappier. In just a few lines of code, you can drastically cut response sizes and speed up delivery, especially for users on mobile or slow networks.
Personally, I apply gzip only to responses over 25 KB, just my preference, since I love my CPU! 😄
If you’re wondering whether gzip has been applied to your API responses, you can easily check this using Chrome DevTools:
Ctrl+Shift+I).Content-Encoding header. If it says gzip, you know your response is compressed.If you enjoyed this article, please make sure to Like, Comment and follow me on Twitter.