Place google ads in the middle of next-mdx-remote

Place google ads in the middle of next-mdx-remote

By: Niraj Dhungana

Nov 24 2021

#MDXRemote# Next JS# Markdown


If you are a programmer and you want to create a blog then nothing is better then Next JS and markdown. If you do so then there is nothing better than next-mdx-remote to render markdown inside your Next JS app.

In the previous post we saw how we can place ads through google adsense inside the Next JS website. Now let's see how we can render google ads in the middle of next-mdx-remote.

Custom component inside MDXRemote

visualizations of injecting custom component to MDX Remote

Here I am going to use the custom Adsense component which I made in the previous post. So, I highly recommend you guys to at least look at the code which we wrote in this post.

If you guys don’t know or it is nice if you already know this thing. The thing is inside next-mdx-remote we can inject custom JSX components.

I hope you already did all the things like serialize and all to render markdown inside MDXRemote. Now I will show you how you can render the Adsense component or your custom adsense component in the middle of other markdown or inside MDXRemote.

1import { MDXRemote } from "next-mdx-remote";
2export default function PostDetail(){
3  return (
4	<div className="wrapper">
5		// Your custom component should be <Adsense />
6		// Or change the component name if you are using different.
7  		<MDXRemote {...source} components={{ Adsense: AdsenseComponent }} />
8	</div>

Now this is how we can inject our custom JSX component inside next-mdx-remote. Let’s create our AdsenseComponent.

1const AdsenseComponent = (props) => {
2  return (
3    <div className="YOU_CAN_ADD_STYLES_ALSO(margin/padding)">
4      <Adsense {...props} />
5    </div>
6  );

The thing is now if you put <Adsense /> in the middle of your markdown. You will see google ads. Sometimes it takes time or you can check the console. If you don’t have any error related to google adsense. Then you are good to go.

1// My sweet markdown with ad
2const markdown = `## This is the markdown heading
3	I am writing some post here.
4	<Adsense />
5	Now ^ is the place where you will see google ad.

If you have any doubt or suggestion you can DM me on @ndpniraj.


Niraj Dhungana

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