Using ES2015 Proxies

A few hours ago I delivered a workshop in SDD conference which is called “Building Scalable JavaScript Apps”. During the workshop I explained to the attendees what are ES2015 proxies and most of them didn’t know that this feature exist. So I decided to write a short post to introduce this API to you.

What are ES2015 Proxies?

The new proxy API enables you to create a handler that wraps an object, intercept it’s properties usage and to defines custom behavior on top of those properties. Proxies can be used to apply contracts for object properties usage, interception for business rules, profiling, logging and more. For example, you can set a rule in a proxy that returns some value instead of undefined if a property that doesn’t exists on an object is being accessed. Other usage example can be some validation rules that you want to set on an object properties before they are being set.

In order to create a proxy you will use the Proxy object and pass it the target object and a handler object that includes the custom behavior you want to add. The following example shows you how to do that:

let target = {};
let proxy = new Proxy(target, {});

In the example above the proxy is created with an empty handler and therefore is doing nothing. Let’s see a much more interesting usage example:

let validator = {
set: function(obj, prop, value) {
if (prop === 'credits') {
if (!Number.isInteger(value)) {
throw 'Supplied credits must be an integer';
if (value < 0 || value > 5) {
throw 'Credits should be between 0 and 5';
obj[prop] = value;
return true;

let course = new Proxy({}, validator);

course.credits = 1;
console.log(course.credits); // prints to the console 1
course.credits = 6; // Throws an exception

In the example the handler, which is called validator will run whenever someone tries to set the target credits property. In the set function which is receiving 3 arguments (the object itself, the property name and the value to set), we check the property name and if it’s credits we run the business rules.

You aren’t limited only to property setters or getters functionality but rather you have a lot of traps that you can set on an object. In proxy terminology a trap is the function that provides property access. You can set traps for functions such as getOwnPropertyDescriptor, defineProperty or deleteProperty. All these traps can help you to create sophisticated custom behaviors in your code.


ES2015 proxies gives you an extension point to intercept object functionality and add custom behavior to the object functionality. Proxies are widely supported in the major browsers (except IE and Opera mini) so you won’t have problems if you will start using them today. If you want a deep dive into ES2015 proxies abilities you can go to MDN.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.