Bird
Raised Fist0
NextJSframework~20 mins

Dynamic OG images in NextJS - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dynamic OG Image Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What does this Next.js dynamic OG image component render?

Consider this Next.js API route that generates a dynamic OG image using the @vercel/og library. What will be the output image's text content if the query parameter ?title=Hello%20World is passed?

NextJS
import { ImageResponse } from '@vercel/og';

export const runtime = 'edge';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title') || 'Default Title';

  return new ImageResponse(
    (
      <div style={{
        backgroundColor: 'black',
        height: '100%',
        width: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        color: 'white',
        fontSize: 48,
        fontWeight: 'bold',
      }}>
        {title}
      </div>
    ),
    {
      width: 1200,
      height: 630,
    }
  );
}
AAn image with white background and black text 'Hello World' centered
BAn image with black background and white text 'title' centered
CAn image with black background and white text 'Default Title' centered
DAn image with black background and white text 'Hello World' centered
Attempts:
2 left
💡 Hint

Look at how the title variable is set and used inside the JSX.

📝 Syntax
intermediate
2:00remaining
Which option fixes the syntax error in this dynamic OG image code?

This Next.js API route code snippet has a syntax error. Which option fixes it correctly?

NextJS
import { ImageResponse } from '@vercel/og';

export const runtime = 'edge';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title') || 'Default Title'

  return new ImageResponse(
    <div style={{ backgroundColor: 'black' }}>{title}</div>,
    {
      width: 1200,
      height: 630,
    }
  );
}
AAdd a semicolon after the title assignment line
BChange <div> to <div></div> with closing tag
CWrap the JSX in parentheses after return
DAdd async keyword before function GET
Attempts:
2 left
💡 Hint

JSX expressions returned directly must be wrapped in parentheses if multiline.

🔧 Debug
advanced
2:00remaining
Why does this dynamic OG image API route return a 500 error?

Given this Next.js API route code for dynamic OG images, why does it return a 500 Internal Server Error when accessed?

NextJS
import { ImageResponse } from '@vercel/og';

export const runtime = 'edge';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title');

  return new ImageResponse(
    <div style={{ backgroundColor: 'black', color: 'white' }}>
      {title.toUpperCase()}
    </div>,
    {
      width: 1200,
      height: 630,
    }
  );
}
AImageResponse requires a string, but JSX is passed instead
Btitle is null if query param missing, so calling toUpperCase() causes error
CMissing await before new ImageResponse causes runtime error
DThe runtime 'edge' is not supported for this API route
Attempts:
2 left
💡 Hint

Consider what happens if the title query parameter is not provided.

❓ state_output
advanced
2:00remaining
What is the width and height of the generated OG image?

In this Next.js dynamic OG image API route, what are the dimensions of the generated image?

NextJS
import { ImageResponse } from '@vercel/og';

export const runtime = 'edge';

export async function GET(request) {
  return new ImageResponse(
    <div style={{ backgroundColor: 'blue', color: 'white' }}>Test</div>,
    {
      width: 1200,
      height: 630,
    }
  );
}
AWidth 1200px and height 630px
BWidth 630px and height 1200px
CWidth 1024px and height 768px
DWidth 800px and height 600px
Attempts:
2 left
💡 Hint

Check the options object passed to ImageResponse.

🧠 Conceptual
expert
3:00remaining
Which statement about Next.js dynamic OG images is true?

Choose the correct statement about generating dynamic OG images in Next.js using the @vercel/og package and edge runtime.

AUsing the edge runtime allows generating OG images on-demand with low latency at the CDN edge
BDynamic OG images can only be generated at build time, not on-demand at request time
CThe <code>ImageResponse</code> component requires a React class component as input
DDynamic OG images cannot include custom fonts or styles
Attempts:
2 left
💡 Hint

Think about the benefits of edge runtime and @vercel/og for image generation.

Practice

(1/5)
1. What is the main purpose of dynamic OG images in Next.js?
easy
A. To create custom preview images automatically based on URL data
B. To improve server response time by caching images
C. To replace all static images with animated GIFs
D. To generate CSS styles dynamically for components

Solution

  1. Step 1: Understand OG images

    OG images are preview pictures shown when sharing links on social media.
  2. Step 2: Role of dynamic OG images in Next.js

    Dynamic OG images let you create these previews automatically using URL parameters, making each preview unique.
  3. Final Answer:

    To create custom preview images automatically based on URL data -> Option A
  4. Quick Check:

    Dynamic OG images = Custom previews [OK]
Hint: Dynamic OG images create previews from URL info [OK]
Common Mistakes:
  • Thinking dynamic OG images improve server speed
  • Confusing OG images with CSS or animations
  • Assuming all images become GIFs automatically
2. Which Next.js import is required to create a dynamic OG image?
easy
A. import { generateImage } from 'next/api';
B. import { createImage } from 'next/image';
C. import { DynamicImage } from 'next/og';
D. import { ImageResponse } from 'next/server';

Solution

  1. Step 1: Identify the correct import for OG images

    Next.js provides ImageResponse from 'next/server' to build dynamic OG images.
  2. Step 2: Check other options

    Other imports like createImage, DynamicImage, or generateImage do not exist or are incorrect for this purpose.
  3. Final Answer:

    import { ImageResponse } from 'next/server'; -> Option D
  4. Quick Check:

    ImageResponse import = import { ImageResponse } from 'next/server'; [OK]
Hint: Use ImageResponse from next/server for OG images [OK]
Common Mistakes:
  • Using imports from 'next/image' instead of 'next/server'
  • Assuming 'next/og' or 'next/api' provide OG image tools
  • Misspelling ImageResponse or import path
3. Given this Next.js API route code snippet for dynamic OG images, what will be the output image text if the URL query is ?title=Hello?
import { ImageResponse } from 'next/server';

export const runtime = 'edge';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const title = searchParams.get('title') || 'Default';

  return new ImageResponse(
    (
      <div style={{
        backgroundColor: 'white',
        width: '100%',
        height: '100%',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        fontSize: 48,
        color: 'black'
      }}>
        {title}
      </div>
    ),
    { width: 1200, height: 630 }
  );
}
medium
A. An image with the text 'Default' centered
B. An image with the text 'Hello' centered
C. An image with no text displayed
D. A runtime error due to missing title parameter

Solution

  1. Step 1: Extract the title from URL query

    The code gets the 'title' parameter from the URL. If missing, it defaults to 'Default'. Here, the query is '?title=Hello', so title = 'Hello'.
  2. Step 2: Render the image with the title text

    The ImageResponse renders a div with the title text centered. Since title is 'Hello', the image will show 'Hello' centered.
  3. Final Answer:

    An image with the text 'Hello' centered -> Option B
  4. Quick Check:

    title param 'Hello' = text shown [OK]
Hint: Check URL param, fallback used only if missing [OK]
Common Mistakes:
  • Assuming 'Default' shows even when title is provided
  • Thinking missing text causes error
  • Ignoring the URL query parameters
4. Identify the error in this Next.js dynamic OG image code snippet:
import { ImageResponse } from 'next/server';

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name');

  return new ImageResponse(
    (
      <div style={{ fontSize: 40 }}>
        Welcome, {name.toUpperCase()}!
      </div>
    ),
    { width: 800, height: 400 }
  );
}
medium
A. Calling toUpperCase() on null if 'name' is missing causes an error
B. ImageResponse must be imported from 'next/image' instead of 'next/server'
C. The style object cannot be used inside JSX for ImageResponse
D. The GET function must be synchronous, not async

Solution

  1. Step 1: Check usage of name variable

    The code calls name.toUpperCase() without checking if name is null. If the URL has no 'name' parameter, name is null, causing a runtime error.
  2. Step 2: Verify other parts

    Import from 'next/server' is correct. Style objects are allowed in JSX for ImageResponse. The GET function can be async.
  3. Final Answer:

    Calling toUpperCase() on null if 'name' is missing causes an error -> Option A
  4. Quick Check:

    Null check missing before toUpperCase() [OK]
Hint: Always check for null before string methods [OK]
Common Mistakes:
  • Assuming name is always present
  • Confusing import source for ImageResponse
  • Thinking style objects are disallowed in JSX
5. You want to create a dynamic OG image in Next.js that shows a user's name and their score from URL parameters. The score should show 'N/A' if missing or zero. Which code snippet correctly implements this logic? A:
const score = searchParams.get('score') || 'N/A';
const displayScore = score === 0 ? 'N/A' : score;
B:
const score = Number(searchParams.get('score'));
const displayScore = score ?? 'N/A';
C:
const score = Number(searchParams.get('score'));
const displayScore = score > 0 ? score : 'N/A';
D:
const score = searchParams.get('score');
const displayScore = score === null || score === 0 ? 'N/A' : score;
hard
A. Option A
B. Option B
C. Option C
D. Option D

Solution

  1. Step 1: Understand the requirement for score

    The score should be shown as a number if positive, otherwise 'N/A' if missing or zero.
  2. Step 2: Analyze each option

    Snippet A uses string fallback and compares score === 0 but score is string, so '0' === 0 false and displays '0'.
    Snippet B converts score to number but uses ?? which only replaces null/undefined, not 0 or NaN, so displays 0 for score=0.
    Snippet C converts score to number and uses a clear check: if score > 0 show score else 'N/A'. This matches requirement perfectly.
    Snippet D compares score as string with === 0, but '0' === 0 false, so displays '0'.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Number conversion + >0 check = Option C [OK]
Hint: Convert to number and check > 0 for score display [OK]
Common Mistakes:
  • Not converting score to number before comparison
  • Using nullish coalescing (??) that ignores zero
  • Comparing string '0' instead of numeric zero
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard