I’m working on my portfolio using the Notion API and Next.js. I’ve run into a problem with displaying cover images. When I use Notion’s hosted images, they expire after a while. But when I try to use an external link for the cover image, my code breaks.
Here’s what I’ve tried:
function CoverImage({ imageUrl }) {
return <img src={imageUrl} alt="Cover" />;
}
This works fine for Notion-hosted images, but not for external ones. I’ve looked at the Notion API docs, but I’m not sure how to handle external links properly.
Has anyone dealt with this before? How can I make my code work for both Notion-hosted and external cover images? Any tips or examples would be really helpful. Thanks!
I’ve encountered a similar issue while building my portfolio with the Notion API. In my case, setting up a custom image handler on the server side solved the problem. I created a simple API route in Next.js to handle all image requests. The route determines whether the image URL is from Notion or an external source. When it’s a Notion URL, the server proxies the request, thus avoiding CORS problems. For external URLs, the server fetches the image, temporarily stores it, and serves it back. Although this added a bit of complexity, it greatly improved the reliability of my portfolio. I also implemented caching to lighten the server load and improve load times.
I faced a similar issue when building my portfolio with Notion API and Next.js. The solution I found was to create a middleware function that checks the image URL before rendering. If it’s a Notion-hosted image, you can use it directly. For external links, you might need to fetch the image and store it on your own server or a CDN.
Here’s a basic approach I used:
async function getImageUrl(url) {
if (url.startsWith('https://www.notion.so')) {
return url; // Notion-hosted image
} else {
// Fetch and store external image
// Return new URL
}
}
function CoverImage({ imageUrl }) {
const [finalUrl, setFinalUrl] = useState(null);
useEffect(() => {
getImageUrl(imageUrl).then(setFinalUrl);
}, [imageUrl]);
return finalUrl ? <img src={finalUrl} alt="Cover" /> : null;
}
This approach helped me handle both types of images seamlessly. Remember to implement proper error handling and caching for better performance.