Version: 3.0.0

NextJS integration

NextJS

Caravaggio can be integrated with NextJS to easily tranform images contained in your project and external images. By using Caravaggio you're able to apply all Caravaggio transformations and to create cached version of these images. Differently from other image resize plugins, Caravaggio doesn't affect your build process delegating the production of cached images on the first request. If you want an in-depth explanation and details about this tecnique, read the article NextJS + Caravaggio, serve images like a rockstar!.

Integration

Here a quick explanation of the integration steps, but read the article for a more complete description.

Install dependencies

In your NextJS project install these dependencies

npm install caravaggio caravaggio-react caravaggio-plugin-nextjs

Create an api page

touch pages/api/assets/[...params].ts

and put this content

// pages/api/assets/[...params].ts
import caravaggio from 'caravaggio';
import nextPlugin from 'caravaggio-plugin-nextjs';
const ONE_DAY = 60 * 60 * 24;
export default caravaggio({
logger: {
options: {
level: "error",
},
},
basePath: "/api/assets",
browserCache: `s-maxage=${ONE_DAY}`,
plugins: {
plugins: [{
name: 'nextjs',
instance: nextPlugin()
}]
}
});

In your _app.js (or .ts), use the CaravaggioProvider

// pages/_app.tsx (or .jsx)
import { AppProps } from "next/app";
import { CaravaggioProvider } from "caravaggio-react";
export default function MyApp({ Component, pageProps }: AppProps) {
return (
<CaravaggioProvider url="/api/assets">
<Component {...pageProps} />
</CaravaggioProvider>
);
}

That's all. You can now use components from caravaggio-react to use all Caravaggio transformations

import { Image } from 'caravaggio-react';
<Image
src="/school.png"
alt="A nice school building"
opt={{
o: "jpg",
progressive: true,
rs: {
s: "300x",
},
}}
/>