Next.js
Installation
Next.js 13.2.1 or higher is required in order to use
react-tweet.
Follow the installation docs in the Introduction.
Usage
In any component, import Tweet from react-tweet and use it like so:
import { Tweet } from 'react-tweet'
export default function Page() {
return <Tweet id="2040511285998313827" />
}Tweet works differently depending on where it’s used. If it’s used in the App Router it will fetch the tweet in the server. If it’s used in the pages directory it will fetch the tweet in the client with SWR .
You can learn more about Tweet in the Twitter theme docs. And you can learn more about the usage in Running the test app.
Troubleshooting
If you see an error saying that CSS can’t be imported from node_modules in the pages directory. Add the following config to next.config.js:
transpilePackages: ['react-tweet']The error won’t happen if the App Router is enabled, where Next.js supports CSS imports from node_modules.
Enabling cache
It’s recommended to enable cache for the Twitter API if you intend to go to production. This is how you can do it with unstable_cache:
import { Suspense } from 'react'
import { unstable_cache } from 'next/cache'
import { TweetSkeleton, EmbeddedTweet, TweetNotFound } from 'react-tweet'
import { getTweet as _getTweet } from 'react-tweet/api'
const getTweet = unstable_cache(
async (id: string) => _getTweet(id),
['tweet'],
{ revalidate: 3600 * 24 },
)
const TweetPage = async ({ id }: { id: string }) => {
try {
const tweet = await getTweet(id)
return tweet ? <EmbeddedTweet tweet={tweet} /> : <TweetNotFound />
} catch (error) {
console.error(error)
return <TweetNotFound error={error} />
}
}
const Page = async ({ params }: { params: Promise<{ tweet: string }> }) => {
const { tweet } = await params
return (
<Suspense fallback={<TweetSkeleton />}>
<TweetPage id={tweet} />
</Suspense>
)
}
export default PageThis can prevent getting your server IPs rate limited if they are making too many requests to the Twitter API.
Advanced usage
Manual data fetching
You can use the getTweet function from react-tweet/api to fetch the tweet manually. This is useful for SSG pages and for other Next.js data fetching methods in the pages directory.
For example, using getStaticProps in pages/[tweet].tsx to fetch the tweet and send it as props to the page component:
import { useRouter } from 'next/router'
import { getTweet, type Tweet } from 'react-tweet/api'
import { EmbeddedTweet, TweetSkeleton } from 'react-tweet'
export async function getStaticProps({
params,
}: {
params: { tweet: string }
}) {
const tweetId = params.tweet
try {
const tweet = await getTweet(tweetId)
return tweet ? { props: { tweet } } : { notFound: true }
} catch (error) {
return { notFound: true }
}
}
export async function getStaticPaths() {
return { paths: [], fallback: true }
}
export default function Page({ tweet }: { tweet: Tweet }) {
const { isFallback } = useRouter()
return isFallback ? <TweetSkeleton /> : <EmbeddedTweet tweet={tweet} />
}Adding next/image
Add the domain URLs from Twitter to images.remotePatterns in next.config.js:
/** @type {import('next').NextConfig} */
const nextConfig = {
images: {
remotePatterns: [
{ protocol: 'https', hostname: 'pbs.twimg.com' },
{ protocol: 'https', hostname: 'abs.twimg.com' },
],
},
}In tweet-components.tsx or elsewhere, import the Image component from next/image and use it to define custom image components for the tweet:
import Image from 'next/image'
import type { TwitterComponents } from 'react-tweet'
export const components: TwitterComponents = {
AvatarImg: (props) => <Image {...props} />,
MediaImg: (props) => <Image {...props} fill unoptimized />,
}Then pass the components prop to Tweet:
import { Tweet } from 'react-tweet'
import { components } from './tweet-components'
export default function Page() {
return <Tweet id="2040511285998313827" components={components} />
}Running the test app
Clone the react-tweet repository and then run the following command:
pnpm install && pnpm dev --filter=next-app...The app will be up and running at http://localhost:3001 for the Next.js app example .
The app shows the usage of react-tweet in different scenarios:
- localhost:3001/light/2040511285998313827 renders the tweet in the app router.
- localhost:3001/dark/2040511285998313827 renders the tweet using SSG in the pages directory.
- localhost:3001/light/mdx rendes the tweet in MDX (with the experimental
mdxRsconfig enabled). - localhost:3001/light/suspense/2040511285998313827 renders the tweet with a custom
Suspensewrapper. - localhost:3001/dark/swr/2040511285998313827 uses
apiUrlto change the API endpoint from which the tweet is fetched in SWR mode. - localhost:3001/light/cache/2040511285998313827 renders the tweet while caching the tweet data with
unstable_cache. - localhost:3001/light/vercel-kv/2040511285998313827 renders the tweet while caching the tweet data with Vercel KV .
The source code for react-tweet is imported from packages/react-tweet and any changes you make to it will be reflected in the app immediately.