I’m building a personal website using Next.js with Notion as my CMS backend. Everything works fine when I use images that are uploaded directly to Notion, but I’m running into problems with external cover images.
When I try to display cover images using something like <img src={page.cover.file.url}/>, my application crashes if the cover was added from an external URL instead of being uploaded to Notion.
I know that Notion images have expiration dates, which is why I want to use external links. But I can’t figure out how to properly detect and handle external cover images versus uploaded ones.
Has anyone dealt with this before? I need a way to check if a cover image is external or uploaded, and handle each case differently in my React component.
Any help would be really appreciated!
Check the cover object structure first - external images use a different property path than uploaded ones. External covers reside at page.cover.external.url while uploaded images are at page.cover.file.url. It’s essential to check page.cover.type initially, as it’ll indicate whether it’s “external” or “file”. I encountered this same issue last year and resolved it using a straightforward conditional check before rendering: const imageUrl = page.cover.type === 'external' ? page.cover.external.url : page.cover.file.url. This approach effectively eliminates crashes from accessing the incorrect property path and handles both scenarios smoothly.
Had this exact issue migrating my blog from WordPress to Notion. Here’s what I figured out: Notion’s API returns totally different object structures for external vs uploaded images. I wrote a helper function that grabs the image URL no matter what type it is: function getCoverUrl(cover) { if (!cover) return null; return cover.type === 'external' ? cover.external?.url : cover.file?.url; } The optional chaining prevents crashes when properties don’t exist. Also throw error boundaries around your image components - external URLs can still fail to load even when detected properly. The optional chaining is key because sometimes the cover object comes back malformed or incomplete from the API.
yeah, ran into this exact issue when I started with notion’s api. you need to check page.cover?.type before grabbing the url properties. external covers don’t have a file object, so they’ll break your code. i just use if (page.cover?.type === 'file') and throw in a placeholder image for external or missing covers.
This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.