Blog
Lessons from opensource: Use Object.defineProperty to create an unwritable object’s property.

Lessons from opensource: Use Object.defineProperty to create an unwritable object’s property.

These lessons are picked from next.js open source code. In this article, you will learn how to create an unwritable property using Object.defineProperty.

Object.defineProperty

Object.defineProperty() is used to add a new property directly to an object.

If you are looking to practice next.js, checkout my website: https://tthroo.com/

Execute the following in your browser’s console.

const object1 = {};

Object.defineProperty(object1, 'property1', {
  value: 42,
  writable: false,
});

Try to make the following modification using the same console:

object1.property1 = 11

Because writable is set to false, you are not able to modify the property1 value. MDN docs has awesome documentation about this.

Object.defineProperty has data descriptor like shown in the above image and accessor descriptor (this is what is used in next.js source code explained below)

Where is Object.defineProperty used in nextjs codebase?

You can find Object.defineProperty used in next.js code here.

https://github.com/vercel/next.js/blob/canary/packages/next/src/client/router.ts#L89

Conclusion:

You do not have the flexibility to make a property unwritable when you create an object using const obj = . In case, if you ever need to have an unwritable property in an object, use Object.defineProperty with unwritable set to false.

About me:

Hey, my name is Ramu Narasinga. I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.

I am open to work on interesting projects. Send me an email at ramu.narasinga@gmail.com

My Github —  https://github.com/ramu-narasinga

My website —  https://ramunarasinga.com

My Youtube channel —  https://www.youtube.com/@ramu-narasinga

Learning platform —  https://thinkthroo.com

Codebase Architecture —  https://app.thinkthroo.com/architecture

Best practices —  https://app.thinkthroo.com/best-practices

Production-grade projects —  https://app.thinkthroo.com/production-grade-projects