How to embed Youtube Videos inside Next MDX

By: Niraj Dhungana

Jul 11 2022



If you are using Next.js for your blog app. Then there is a higher chance you are using markdown for your content and there is an even higher chance you are using next-mdx-remote to render those markdown contents.

When using markdown the only drawback is that we can not embed videos or other content. But that was past now you can and you will after going through this tutorial.

If you notice at the top of this post we have a Youtube video and the good thing is that behind the scene I am using next js with markdown to add these contents. So if you want a detailed overview you can watch the video itself.

Adding Custom Components

First of all, for this, we have to create a custom component that can render Youtube videos with the id that we will provide.

For that, you can use the given code for the demo. Also, you can add your custom styles to give it the look that you want.

1// YouTube.tsx
2const YouTube: FC<{ id: string }> = ({ id }) => {
3  return (
4    <div>
5      <iframe
6        width="100%"
7        height="450"
8        src={"" + id}
9        title="YouTube video player"
10        frameBorder="0"
11        allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
12      ></iframe>
13    </div>
14  );

Here I am using typescript if you are using javascript you can remove those types or just copy the return statement and paste it inside your YouTube.jsx.

Once you have your component ready with us we can attach it to the mdx-next-remote.

1// inside your PostDetail.tsx
2import { MDXRemoteSerializeResult } from "next-mdx-remote";
3import YouTube from "./YouTube.tsx";
5const components = {
6    YouTube
9const PostDetail: FC<{ source: MDXRemoteSerializeResult }> = () => {
10    return <MDXRemote components={components} {...source} />

Note:- Make sure you are using the exact same name for your component. Like we have a component called <YouTube /> and we are passing that same component as YouTube. If you have <YoutubeElement /> then you have to use this same name YoutubeElement.

So simple right, yeah man that's it. Now you should have the youtube videos embedded inside your Next-MDX.


Niraj Dhungana

I hope you enjoyed reading this post and learned something new. If not then tell me how can I improve. @fsniraj