Next.js course ยท Module 8: Deployment and Production
Open Graph and sharing on social media platforms
In this lesson9
Proper content sharing on social media is a key element of the marketing and SEO strategy of any modern application. Protocols such as Open Graph and Twitter Cards allow control over the appearance of shared links, which significantly increases their attractiveness and effectiveness. In this chapter, you will learn how to optimize your Next.js application for social media sharing.
What is the Open Graph Protocol?
Open Graph Protocol (OGP) is a technology developed by Facebook that enables any web page to become a rich object on social media. When a user shares a link to your page on Facebook, LinkedIn, or other social media platforms, the OG protocol determines what information and visual elements should be displayed.
Basic Open Graph tags
The basic set of Open Graph tags includes:
- og:title - content title
- og:type - content type (e.g., website, article, product)
- og:image - URL of the image that should represent the content
- og:url - canonical URL of the content
Additional useful tags include:
- og:description - short content description
- og:site_name - site name
- og:locale - content language (e.g., pl_PL)
Twitter Cards
Twitter Cards is a similar technology, specific to the Twitter (X) platform, which controls how shared content is displayed. The most important tags are:
- twitter:card - card type (summary, summary_large_image, app, player)
- twitter:title - content title
- twitter:description - content description
- twitter:image - image to display
- twitter:site - site account name (@sitename)
- twitter:creator - content author's account name (@author)
Implementing Open Graph in Next.js
Next.js 13+ significantly simplifies the implementation of the Open Graph protocol through the new Metadata API. Here's how to do it:
Basic implementation
// app/page.tsx
import { Metadata } from 'next';
export const metadata: Metadata = {
openGraph: {
title: 'My Next.js application',
description: 'Discover the capabilities of our application',
url: 'https://twojadomena.pl',
siteName: 'Your Site Name',
images: [
{
url: 'https://twojadomena.pl/og-image.jpg',
width: 1200,
height: 630,
alt: 'My Next.js application',
},
],
locale: 'pl_PL',
type: 'website',
},
twitter: {
card: 'summary_large_image',
title: 'My Next.js application',
description: 'Discover the capabilities of our application',
images: ['https://twojadomena.pl/twitter-image.jpg'],
creator: '@twojanazwa',
site: '@twojapage',
},
};
export default function Home() {
return (
<main>
{/* Page content */}
</main>
);
}Dynamic Open Graph metadata
For dynamic pages, such as blog articles or products, we can generate Open Graph metadata based on data from the API or database:
// app/blog/[slug]/page.tsx
import { Metadata } from 'next';
import { getBlogPost } from '@/lib/api';
export async function generateMetadata({ params }): Promise<Metadata> {
const post = await getBlogPost((await params).slug);
if (!post) {
return {
openGraph: {
title: 'Post not found',
description: "Sorry, we didn't find the article you were looking for",
type: 'article',
},
};
}
// Basic information
const title = `${post.title} | Blog My Application`;
const description = post.excerpt;
const url = `https://twojadomena.pl/blog/${post.slug}`;
// Open Graph metadata for the article
return {
openGraph: {
title: title,
description: description,
url: url,
siteName: 'Your Site Name',
images: [
{
url: post.coverImage || 'https://twojadomena.pl/default-og.jpg',
width: 1200,
height: 630,
alt: post.title,
},
],
locale: 'pl_PL',
type: 'article',
publishedTime: post.publishedAt,
authors: post.author.name,
tags: post.tags,
},
twitter: {
card: 'summary_large_image',
title: title,
description: description,
images: [post.coverImage || 'https://twojadomena.pl/default-twitter.jpg'],
creator: post.author.twitter || '@twojanazwa',
site: '@twojapage',
},
};
}
export default async function BlogPost({ params }) {
const post = await getBlogPost((await params).slug);
if (!post) {
return <div>Post not found</div>;
}
return (
<article>
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.content }} />
</article>
);
}Creating and optimizing images for social media
Each social media platform has its recommended image dimensions. Preparing images in accordance with these guidelines ensures the best experience when sharing:
Recommended image dimensions
Facebook/Open Graph:
- Recommended: 1200 ร 630 pixels
- Minimum: 600 ร 315 pixels
- Aspect ratio: 1.91:1
Twitter:
- Large card (summary_large_image): 1200 ร 628 pixels
- Regular card (summary): 800 ร 418 pixels
LinkedIn:
- Recommended: 1200 ร 627 pixels
- Aspect ratio: 1.91:1
Pinterest:
- Recommended: 1000 ร 1500 pixels
- Aspect ratio: 2:3
Dynamic Open Graph image generation
Instead of manually creating images for each page, we can generate them dynamically using API Routes in Next.js. This is a great solution for applications with many dynamic pages, such as e-commerce or blogs:
// app/api/og/route.tsx
import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
export const runtime = 'edge';
export async function GET(req: NextRequest) {
const { searchParams } = new URL(req.url);
// Get parameters from the URL
const title = searchParams.get('title') || 'My Application';
const description = searchParams.get('description') || 'Default description';
const imageUrl = searchParams.get('image');
// Define colors, fonts, and style
const bgColor = '#111827';
const textColor = '#ffffff';
// Fonts can also be loaded dynamically
// const font = await fetch('...').then(res => res.arrayBuffer());
return new ImageResponse(
(
<div
style={{
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
width: '100%',
height: '100%',
backgroundColor: bgColor,
color: textColor,
padding: '40px',
position: 'relative',
}}
>
{imageUrl && (
<img
src={imageUrl}
style={{
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%',
objectFit: 'cover',
opacity: 0.6,
}}
/>
)}
<div
style={{
display: 'flex',
flexDirection: 'column',
zIndex: 10,
maxWidth: '80%',
textAlign: 'center',
}}
>
<h1 style={{ fontSize: '64px', fontWeight: 'bold', marginBottom: '20px' }}>
{title}
</h1>
<p style={{ fontSize: '32px', margin: 0 }}>
{description}
</p>
<div style={{
marginTop: '40px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
}}>
<img
src="https://twojadomena.pl/logo.png"
width="60"
height="60"
style={{ marginRight: '20px' }}
/>
<p style={{ fontSize: '36px', fontWeight: 'bold' }}>mojadomena.pl</p>
</div>
</div>
</div>
),
{
width: 1200,
height: 630,
// Optionally you can apply fonts
// fonts: [{ name: 'Inter', data: font, weight: 400 }],
},
);
}Using dynamically generated Open Graph images:
// app/blog/[slug]/page.tsx
export async function generateMetadata({ params }) {
const post = await getBlogPost((await params).slug);
const ogImageUrl = new URL('/api/og', 'https://twojadomena.pl');
ogImageUrl.searchParams.append('title', post.title);
ogImageUrl.searchParams.append('description', post.excerpt);
if (post.coverImage) {
ogImageUrl.searchParams.append('image', post.coverImage);
}
return {
openGraph: {
// ...other metadata
images: [
{
url: ogImageUrl.toString(),
width: 1200,
height: 630,
alt: post.title,
},
],
},
//
};
}Social media share buttons
Adding share buttons to your application is an effective way to increase reach. Here's how to implement them in Next.js:
ShareButtons component
// components/ShareButtons.tsx
'use client';
import { usePathname } from 'next/navigation';
import { FaFacebook, FaTwitter, FaLinkedin, FaPinterest, FaEnvelope } from 'react-icons/fa';
interface ShareButtonsProps {
title: string;
description?: string;
imageUrl?: string;
hashtags?: string[];
}
export default function ShareButtons({ title, description, imageUrl, hashtags = [] }: ShareButtonsProps) {
const pathname = usePathname();
// Create the full URL
const baseUrl = 'https://twojadomena.pl';
const url = baseUrl + pathname;
// Encode parameters for sharing
const encodedUrl = encodeURIComponent(url);
const encodedTitle = encodeURIComponent(title);
const encodedDescription = description ? encodeURIComponent(description) : '';
const encodedHashtags = hashtags.length > 0 ? encodeURIComponent(hashtags.join(',')) : '';
// Create share links
const facebookShareUrl = `https://www.facebook.com/sharer/sharer.php?u=${encodedUrl}`;
const twitterShareUrl = `https://twitter.com/intent/tweet?url=${encodedUrl}&text=${encodedTitle}&hashtags=${encodedHashtags}`;
const linkedinShareUrl = `https://www.linkedin.com/sharing/share-offsite/?url=${encodedUrl}`;
const pinterestShareUrl = imageUrl
? `https://pinterest.com/pin/create/button/?url=${encodedUrl}&media=${encodeURIComponent(imageUrl)}&description=${encodedTitle}`
: `https://pinterest.com/pin/create/button/?url=${encodedUrl}&description=${encodedTitle}`;
const emailShareUrl = `mailto:?subject=${encodedTitle}&body=${encodedDescription}%0A%0A${encodedUrl}`;
// Function handling share button click
const handleShare = (url: string) => {
window.open(url, '_blank', 'width=600,height=400');
};
return (
<div className="flex space-x-4 items-center">
<span className="text-sm font-medium text-gray-700">Share: </span>
<button
className="text-blue-600 hover:text-blue-800 transition-colors"
onClick={() => handleShare(facebookShareUrl)}
aria-label="Share on Facebook"
>
<FaFacebook size={24} />
</button>
<button
className="text-sky-500 hover:text-sky-700 transition-colors"
onClick={() => handleShare(twitterShareUrl)}
aria-label="Share on Twitter"
>
<FaTwitter size={24} />
</button>
<button
className="text-blue-700 hover:text-blue-900 transition-colors"
onClick={() => handleShare(linkedinShareUrl)}
aria-label="Share on LinkedIn"
>
<FaLinkedin size={24} />
</button>
<button
className="text-red-600 hover:text-red-800 transition-colors"
onClick={() => handleShare(pinterestShareUrl)}
aria-label="Share on Pinterest"
>
<FaPinterest size={24} />
</button>
<a
href={emailShareUrl}
className="text-gray-600 hover:text-gray-800 transition-colors"
aria-label="Share via email"
>
<FaEnvelope size={24} />
</a>
</div>
);
}Using the ShareButtons component
// app/blog/[slug]/page.tsx
import ShareButtons from '@/components/ShareButtons';
import { getBlogPost } from '@/lib/api';
export default async function BlogPost({ params }) {
const post = await getBlogPost((await params).slug);
if (!post) {
return <div>Post not found</div>;
}
return (
<article className="max-w-2xl mx-auto py-8">
<h1 className="text-3xl font-bold mb-4">{post.title}</h1>
<div className="my-6">
<ShareButtons
title={post.title}
description={post.excerpt}
imageUrl={post.coverImage}
hashtags={post.tags}
/>
</div>
<div className="prose max-w-none" dangerouslySetInnerHTML={{ __html: post.content }} />
<div className="mt-8 pt-4 border-t">
<ShareButtons
title={post.title}
description={post.excerpt}
imageUrl={post.coverImage}
hashtags={post.tags}
/>
</div>
</article>
);
}Integration with the Web Share API
Web Share API is a modern alternative to traditional share buttons, which allows users to share content using any application installed on their device:
// components/NativeShareButton.tsx
'use client';
import { useState, useEffect } from 'react';
import { FaShare } from 'react-icons/fa';
import { usePathname } from 'next/navigation';
interface NativeShareProps {
title: string;
text?: string;
url?: string;
files?: File[];
}
export default function NativeShareButton({ title, text, url, files }: NativeShareProps) {
const [isShareSupported, setIsShareSupported] = useState(false);
const pathname = usePathname();
useEffect(() => {
// Check if the browser supports the Web Share API
setIsShareSupported(
typeof navigator !== 'undefined' &&
!!navigator.share
);
}, []);
// If the browser does not support the Web Share API, do not render the button
if (!isShareSupported) {
return null;
}
const handleShare = async () => {
try {
const shareData: ShareData = {
title,
text: text || title,
url: url || window.location.href,
};
// Add files if they are available and the browser supports them
if (files && navigator.canShare && navigator.canShare({ files })) {
shareData.files = files;
}
await navigator.share(shareData);
console.log('Content has been shared');
} catch (error) {
console.error('Error during sharing:', error);
}
};
return (
<button
onClick={handleShare}
className="flex items-center space-x-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md transition-colors"
aria-label="Share"
>
<FaShare />
<span>Share</span>
</button>
);
}Testing Open Graph and sharing
Proper configuration of Open Graph and Twitter Cards requires testing. Here are the tools that can help:
Debugging tools
- Facebook Sharing Debugger: https://developers.facebook.com/tools/debug/
- Twitter Card Validator: https://cards-dev.twitter.com/validator
- LinkedIn Post Inspector: https://www.linkedin.com/post-inspector/
- Pinterest Rich Pins Validator: https://developers.pinterest.com/tools/url-debugger/
Open Graph test automation
You can automate Open Graph tests as part of the CI/CD process:
// scripts/test-og-tags.mjs
import puppeteer from 'puppeteer';
import { promises as fs } from 'fs';
const pages = [
{ url: '/', name: 'home' },
{ url: '/blog/example-post', name: 'blog-post' },
{ url: '/products/example-product', name: 'product' },
// Add other important pages
];
async function testOgTags() {
const browser = await puppeteer.launch();
const results = [];
try {
for (const page of pages) {
const pageUrl = `https://twojadomena.pl${page.url}`;
const puppeteerPage = await browser.newPage();
await puppeteerPage.goto(pageUrl, { waitUntil: 'networkidle0' });
// Get all Open Graph tags
const ogTags = await puppeteerPage.evaluate(() => {
const tags = {};
const metaTags = document.querySelectorAll('meta[property^="og:"], meta[name^="twitter:"]');
metaTags.forEach(tag => {
const property = tag.getAttribute('property') || tag.getAttribute('name');
const content = tag.getAttribute('content');
tags[property] = content;
});
return tags;
});
// Check required tags
const requiredTags = ['og:title', 'og:description', 'og:image', 'og:url', 'twitter:card'];
const missingTags = requiredTags.filter(tag => !ogTags[tag]);
const result = {
page: page.name,
url: pageUrl,
ogTags,
missingTags,
hasErrors: missingTags.length > 0,
};
results.push(result);
await puppeteerPage.close();
}
// Save the report
await fs.writeFile('./og-tags-report.json', JSON.stringify(results, null, 2));
// Whether all pages have required tags
const hasErrors = results.some(result => result.hasErrors);
if (hasErrors) {
console.error('Missing Open Graph tags found:');
for (const result of results) {
if (result.hasErrors) {
console.error(`Page: ${result.page}`);
console.error(`Missing tags: ${result.missingTags.join(', ')}`);
console.error('---');
}
}
process.exit(1);
} else {
console.log('All required Open Graph tags are present.');
}
} finally {
await browser.close();
}
}
testOgTags().catch(console.error);Best practices and tips
- Optimize images - Use images with appropriate dimensions and proportions for each platform
- Use unique images - Create unique and eye-catching images for important pages
- Add branding - Place logo or visual identity elements on OG images
- Test on different platforms - Check how shared content looks on all major platforms
- Experiment with titles - Test different titles and descriptions to increase CTR from shares
- Update metadata - Regularly refresh metadata for pages with recurring content
Summary
Proper implementation of Open Graph and Twitter Cards protocols and well-designed share buttons can significantly increase the visibility and reach of your Next.js application. Using dynamically generated OG images allows for personalized and attractive display of shared content, and the Web Share API offers a native sharing experience on mobile devices.
Remember that social media platforms often update their requirements and recommendations, so it's worth regularly checking the documentation of each platform and testing content sharing on different devices and browsers.
Docs entries used in this lesson
Spotted a mistake in this lesson?