How to clean text editor data on next.js

Hello, in this post am going to show you how to clean data from a text editor in next.js to ensure that your site stays safe .

Am assuming you already know how to display data from a text editor in your web page, if you don't then i suggest you read our How to render data from a text editor in a next.js web page without template tags post.

Please note in this post i am working with data gotten from django-ckeditor in a django rest framework api.

Alright lets begin

What you have now

If you have read our how to render data from a text editor in a next.js web page without template tags post, then your jsx should look somethng like this

 <span
      dangerouslySetInnerHTML={{__html: post}}>
</span>

Whereby "post" is the data from the text editor.

Step 1

Install "isomorphic-dompurify" package into your next.js app by typing the code below in your terminal and pressing enter

npm i isomorphic-dompurify

We are using isomorphic-dompurify because it will allow us to clean data on the client side i.e in our jsx code.

Step 2

Import dompurify from isomorphic-dompurify as shown below;

import dompurify from "isomorphic-dompurify";

Step 3

Create a constant sanitizer and set it to be equal to dompurify.sanitize as shown below

const sanitizer = dompurify.sanitize;

Step 4

Wrap your text editor data with the sanitizer const as shown below

<span dangerouslySetInnerHTML={{__html: sanitizer(post.body)}}>
</span>

with this the data you get from your text editor gets cleaned first by dompurify before it is rendered in the browser

Conclusion

We have been able to secure the data we get from a text by using a third party package called isomorphic-dompurify in the client side of our code. This works for dynamic data gotten from a backend api as well. As always thanks for reading and if following this post worked successfully or if you ran into an error leave a comment down below and we'll help you work it out.

Author
author-image

Hello, my name is Abubakar Zakari. Am a budding fullstack developer from Nigeria who loves developing softwares and learning new frameworks and langauges.

Comment

Select image


Comments
No comment yet

DEVMAESTERS

Newsletter

Services

Frontend Development |Backend Development |Full Website Development |Bootstrap Website upgrades | Website Debbugging | Website Hosting & deployment

Contact

Interested in hiring me or collaborating with me on a project, click on any of the links below to get my social media handle

Or contact me via Tel: (+234)-806-225-7480 | Email: abubakarzakari1703@gmail.com

Copywright@devmaesters.com
Privacy Policy

By using our website,
you agree that devmaesters can store cookies on your device and disclose information in accordance with our privacy policy.