Use image optimization to improve app performance
When displaying your users' profile images, you should use query parameters to specify a maximum size and minimum quality. Doing so can allow you to improve your app's overall page load times by reducing the file sizes of the images you're fetching.
Add query parameters to imageUrl
Some types in Clerk's JavaScript SDK, such as User
, PublicUserData
, and Organization
, have an imageUrl
. The URL returned from this property can be scaled down with the following image optimization options:
"width"
: Sets the max width of the image in pixels."height"
: Sets the max height of the image in pixels."fit"
: Describes how the image should fit its container. It can take the following values:"scale-down"
: The image will scale down to fit the sizes specified in"width"
and"height"
if it's bigger, but will not scale up if it's smaller."crop"
: The image will scale down and be cropped to fit within the area specified in"width"
and"height"
.
"quality"
: Specifies the image quality for JPEG, WebP, PNG, and AVIF files. Accepts values from1
to100
. Defaults to85
.
Example
The following example demonstrates how you can get the imageUrl
from the currently active user in a session, and display their profile picture using Clerk's image optimization options:
app/image-optimization/page.tsximport { currentUser } from "@clerk/nextjs/server"; export default async function ImageOptimization() { const user = await currentUser(); if (!user) return <p>No Image URL found</p>; const { imageUrl } = user; const params = new URLSearchParams(); params.set("height", "200"); params.set("width", "200"); params.set("quality", "100"); params.set("fit", "crop"); const imageSrc = `${imageUrl}?${params.toString()}`; return ( <div> <h1>Image source:</h1> <p>{imageSrc}</p> <h2>Image:</h2> <img src={imageSrc} alt="User image" /> </div> ); }
components/image-optimization.tsximport { useClerk } from "@clerk/clerk-react"; import React from "react"; export default function ImageOptimization() { const clerk = useClerk(); const { user } = clerk; if (!user) return <p>No Image URL found</p>; const { imageUrl } = user; const params = new URLSearchParams(); params.set("height", "200"); params.set("width", "200"); params.set("quality", "100"); params.set("fit", "crop"); const imageSrc = `${imageUrl}?${params.toString()}`; return ( <div> <h1>Image source:</h1> <p>{imageSrc}</p> <h2>Image:</h2> <img src={imageSrc} alt="User image" /> </div> ); }
Last updated on March 1, 2024