Contentful-Syntax-Highlight
Author Cloudapp
E.G.

Next.js 14 / Contentful- Professional Syntax Highlighting

July 15, 2024
Table of Contents

Now, I will reuse the component I created in the previous story combined with the headless CMS Contentful. So I can create my Content within Contentful and use Next.js 14 for the visualization, which makes my life a lot easier.

Here is the GitHub repo with the entire code. Below, you will find the link to the example page.

Example page hosted on Vercel -> https://nextjs14-contentful-syntax-highlighting.vercel.app/

Direct link to the code block

Used Stack

I will start with my default stack:

  • Next.js 14 as the web framework, and I will use the provided middleware edge function

  • NPM Package Shiki for syntax highlighting and the corresponding transformers package

  • Contentful CMS (Free Plan)

  • Vercel for hosting

New Component for Syntax Highlighting in My Blog Posts

I copied the code from the old component (//src/components/tools/syntax highlight/syntax highlight.component.tsx) that I used on the homepage.

Since I would like to restyle the component for the blog posts, I created a new file //src/components/tools/syntax highlight/syntax highlightPost.component.tsx with this code.

Integration of new component into Contentful Richtext Component

When I am done with this, I will import the newly created component into my main Contentful Rich Text Component under //src/components/CtfRichText.component.tsx

Passing Codeblock to the new Component

The complete magic happens in the [MARKS.CODE] Block

Definition of variable

Showing Codeblock with new syntax highlighting

<SyntaxHighlightPost code={showCodeText} lang="typescript" />

You can also see many comments. These code pieces were used before for the old code block.

Website-Codeblock
Website-Codeblock

Content Management for Syntax Highlighting in Contentful

Below you can see a content record of type “page — Blog post” where I mark the corresponding content block as “Code” in the rich text field “Content”. At the end of each line, which should be formatted specially, I put the right keywords from the Shiki package. That’s it, and now we have a great CMS combined with a nice-looking output on the frontend side, handled by next.js 14.

Contentful-Codeblock
Contentful-Codeblock

Cloudapp-dev, and before you leave us

Thank you for reading until the end. Before you go:

Please consider clapping and following the writer! 👏 on our Medium Account

Or follow us on twitter -> Cloudapp.dev

Related articles