Home Blog Work

Javascript ES6 Proxy

Published on December 2, 2021

In Server side proxy are a interface instead of calling the service directly we would have proxy server where It would forward the request to main service.

We could abstract all the details of the main service or switch between different service int the background.

graph TD;

ES6 Proxy

We could the same with for Javascript Object. We can create a proxy for javascript Object where we can provider a interface for Object to hide internal details of the objects.


const proxy = new Proxy(target, config)

target is what object we want to hide. config is the proxy configuration.

Now, Let’s see how we can configure any object.



const engToSpanish = new Map();
engToSpanish.set('hi', 'Hola');

proxy = new Proxy(engToSpanish, {
	get(target, prop) {
		if(target.has(prop)) {
			return target.get(prop);
		} else {
			return 'Oops! Word not found'

console.log(proxy.hi) // Hola
console.log( // 'Oops! Word not found'


Same way we can also use set function to manipulate target Object.

let numberOnlyArray = [];

proxy = new Proxy(numberOnlyArray, {
	set(target, prop, val) {
		if (typeof val === 'number') {
			target[prop] = val 
			return true;
		} else {
			throw new Error('Oops! Numbers only');
			return false;
proxy.push(1) // 1
proxy.push('hi') // Oops! Numbers only

Don’t forget return true for success.

Other config methods

InternalMethodMethod Triggers when…
[[Get]]getreading a property
[[Set]]setwriting to a property
[[HasProperty]]hasin operator
[[Delete]]deletePropertydelete operator
[[Call]]applyfunction call
[[Construct]]constructnew operator
[[DefineOwnProperty]]definePropertyObject.defineProperty, Object.defineProperties
[[GetOwnProperty]]getOwnPropertyDescriptorObject.getOwnPropertyDescriptor,, Object.keys/values/entries
[[OwnPropertyKeys]]ownKeysObject.getOwnPropertyNames, Object.getOwnPropertySymbols,, Object.keys/values/entries

Read More