Nahuel Sanchez

A place to write down what I discover and learn everyday at my workplace. Front-end may be the main topic, but who knows, probably I'll be publishing something else.

You're looking at all the posts published under the tag VTEX.
← Go back to the front page

How a VTEX developer looks like from a technical point of view

If you happen to be on a similar position as I am where one of my task is to conduct interviews and vote on someone getting hire or not, you also have to be able to establish if that person can work with a specific platform.

It is not the same working on a VTEX store, an ORO implementation, or in a Magento project. For each platform you have to have a specific set of skills, and again, depending on the platform, more experience on some specific skills are necessary and the seniority on a specific ability vary when you change the CMS you are messing with.

VTEX requires a front end developer with a signed certification from his mother saying that he's great with those "Find the n differences" puzzles you get on the Sunday's newspaper, because the primary task he'll face is to transform a given design into "code", as pixel perfect as it can be.

So, how it looks like now?

Translated to actual skills, for a start it means we're looking for someone very good at xHTML, CSS (and/or any CSS preprocessor like SASS or LESS), that can also handle simple JavaScript logic or jQuery for basic UX interactions.

Bear with me if you not agree on that "simple JavaScript logic" statement, because there's a reason why I said "for a start". With this specific developer you are kicking off the team you need for a VTEX implementation but you are not finish yet.

Based on my experience, someone with the ability to handle the layout will cover a high percentage of what the project needs. Seriously, even on highly custom VTEX projects always the largest amount of workload falls on the person who handles the implementation of the designs and that's why is very important to have someone who nails this task.

The next step is to choose between two options: we either look harder for a person with the mentioned skills that can also handle the logical part of a development, or we get another team member for this job only.

If we go for the first option, now finding the developer became a little bit more complicating.

I think that considering a lot of front end developers, on one end we have the "developer who handles the layout and leaves the logic to back end" and in the other side the "kind of full stack developer hungry for programming but with no love for the look and feel".

Our first option requires us to find someone in between, and that's hard (talking, again, from my work experience). Personally I'll go for this option, because, personally, I feel more comfortable with those "in between" developers. But that's just me.

The second option is more suitable when looking at this from a company level where you have multiple VTEX implementations.

Imagine an scenario where you have three VTEX projects ongoing, each with a person assigned full time implementing the layout only, and a fourth developer jumping from VTEX 1, to VTEX 2 and VTEX 3 working on the customizations only, while leaving the "make this as the designs indicate" to the full time assigned coworker.

The person in this second option needs to know JavaScript for real, because all VTEX front end custom stuff always falls on the need of use of JavaScript.

The developer, sort of acting as a back end developer in this platform (in a manner of speaking) will be dealing with the logical part of the implementation like struggling with the APIs and integrating with VTEX's Master Data.

But how it will look like in the future?

The platform is evolving constantly and it is on its peak on what updating the technology stack refers. This means that what I just said above still applies, but we need to consider what is coming.

In the not so distant future the idea of VTEX IO as the VTEX's web application development platform is that custom (and useful) customization that takes places on a specific VTEX store become an App, in a sort of plug and play plugin for that specific store and others.

For example, let's say you have to development something to get the users' email using a form in order to subscribe them to the newsletter configured using MailChimp. Do it once, make it an App, and reuse it on the future or sell it to other existing stores seeking for the same functionality.

In this new world, besides the fact that you need a little bit of npm and the use of a Terminal to set up your workspace, you'll definitely need to know React and GraphQL in order to build the application.

So don't get sleepy.

Understanding the product's name front end logic in VTEX

Is VTEX showing the name from the Product in the Admin? Or is it showing the name we entered in the SKU? Or is it showing both?... or why sometimes it seems like VTEX is using the Product name and in other occasions it is using the SKU name?

In other words, what's the name I'm going to see in the front end of my VTEX store when creating a new product?

I'm writing this down because I found there's always a confusion about what is VTEX showing as a name for a product when looking at it in the front end (like in a category or product's page) considering there's a tricky logic there that involves the Product entity and the SKU.

Product entity name and SKU name?

To avoid any misunderstanding, let's discuss first what I mean by "Product entity name" and what I'm talking about when referring to the "SKU name".

When I say "product's name" we all think about a product as a whole, the item itself and the name that item has. But a product in VTEX is divided into two thing: The Product (or the Product entity) and the SKUs included on that Product.

I know I might sound philosophical and delusional but just take a look at this screenshot so I explain myself better.

understanding-the-products-name-front-end-logic-in-vtex-01-1

Is our site showing the name from the first column or from the second one?

Which one is going to appear on the front end of the VTEX store?

It just depends on this simple logic you need to consider.

If the Product entity name is exactly the same as the SKU name, then VTEX will show only one. Take a look at the screenshot above where the names in both columns are identical, meaning the front end will only show "iPhone X 64GB Silver".

On the other hand, if the name in the Product is different from the name in the SKU, then VTEX will show the two names separated by a dash (-).

For example, if for the Product we have "iPhone X 64GB" and for the SKU we have just "Silver", then the result on the front end it is going to be "iPhone X 64GB - Silver". That simple.

understanding-the-products-name-front-end-logic-in-vtex-02

Knowing that, if you're facing the "problem" in VTEX with the front end showing the names "duplicated" or if you didn't understand from where that final name is coming... now you know.

Keeping both the Product and SKU with the exacly same text (not even a difference in the capital letters) will show only one name, no dash.

Check if a user has made a purchase on a VTEX store

There's no a simple built in functionality on VTEX that allows to check if the current user browsing the store has already made a purchase there, but there's a twisted workaround to get this information.

Before actually going through the guide, this is the idea: we need to create a new attribute in the CL Data Entity that retains this information and this attribute is going to be updated on the Order Placed page doing an HTTP request to the VTEX Master Data using JavaScript.

Sounds simple? Weeell...

Creating the new attribute

Thanks to the VTEX Master Data API we can get a lot of information about the clients, but if he or she has made a purchase is not there anywhere, that's why we need to create a new attribute that will hold this information.

The new attribute, let's name it buyer, needs to be Boolean, and we need to grant it permissions to be read it and edit it using the API.

Attribute configuration on the Client Data Entity

All existing registered users on our store will have it in null or false until we changed it to true after a user performs a full checkout process.

Updating the attribute

After the user performs a purchase he will end on the Order Placed page that says something like "Em breve você receberá um e-mail no endereço john doe@example.com com todos os detalhes do pedido". We need to get that email from the source code of the page and using jQuery AJAX performs a PATCH in order to set the buyer attribute in true.

The problem is that we can't directly insert any piece of JavaScript code in the VTEX Smart Checkout. If you're thinking on adding the JavaScript code into any of the orderplaced-* templates, it won't work, the code won't be displayed because of security reasons.

VTEX Portal section

Here's the fun part: we need to use Google Tag Manager to insert JavaScript on that page.

GTM as our Trojan Horse

Since the VTEX Smart Checkout, as any other checkout process from any other platform, is a sensible part of the site and that's the reason why we don't have, directly on VTEX, a way to insert JavaScript code.

If we have Google Tag Manager integrated into our VTEX store it's our lucky day because that tool can add JavaScript on the page, and the idea is to give to GTM our jQuery AJAX request code.

To accomplish this we need to create a new Custom HTML Tag where instead of HTML we are going to add our script. This script.

$(window).load(function() {
    if ($('.orderplaced-sending-email strong').text().trim()) {
        var urlProtocol = window.location.protocol;
        var apiUrl = urlProtocol + '//api.vtexcrm.com.br/storename/dataentities/CL/documents';

        $.ajax({
            "headers": {
                "Accept": "application/vnd.vtex.masterdata.v10+json",
                "Content-Type": "application/json"
            },
            "url": apiUrl,
            "async" : false,
            "crossDomain": true,
            "type": "PATCH",
            "data": JSON.stringify({
                "email" : $('.orderplaced-sending-email strong').text().trim(),
                "buyer" : true
            })
        });
    }
});

Next, on the Fire on step, click on More in order to create a new trigger. The new trigger needs to be a personalized event that will be fired on "orderPlaced".

GTM new Tag

Save the tag and publish the changes on Google Tag Manager. This is not affected by VTEX cache so we should see the changes immediately.

At this point every time a user hits that page, meaning every time an user finish a purchase, the buyer attribute will be set to true. So now in any other page of the store you can use the VTEX Master Data API to check if buyer is true. If so, then the user browsing the site already made a purchase and you can do whatever you want with that information.

Waaaait

This is a delicate move. You are inserting JavaScript into the checkout process so test it very well, you don't want to screw this part of the VTEX implementation.

Code to GET, POST, PATCH and PUT data in VTEX Master Data

We can manipulate the documents existing in the VTEX Master Data using HTTP request, and it's like the most important thing we should know to dominate this platform's tool.

The official Master Data API documentation breaks down the different HTTP request we can use and explains each part of the request but this information wasn't enought for me to create a working code.

Using and old technique known as "try and failure" I came up with four working jQuery AJAX requests ready to be used to GET, POST, PATCH and PUT data in a specific Data Entity.

My goal was to simplify the interaction with the VTEX Master Data during the implementation of a VTEX store. The code is far from perfect but it's a working start.

GET

function getFromMasterData(name, where, fields) {
    var store = 'storeName';
    var urlProtocol = window.location.protocol;
    var apiUrl = urlProtocol + '//api.vtex.com/' + store + '/dataentities/' + name + '/search?_where=' + where + '&_fields='+ fields;
    var response;

    $.ajax({
        "headers": {
            "Accept": "application/vnd.vtex.masterdata.v10.profileSchema+json"
        },
        "url": apiUrl,
        "async" : false,
        "crossDomain": true,
        "type": "GET"
    }).success(function(data) {
        response = data[0];
    }).fail(function(data) {
        response = data;
    });

    return response;
}

The first parameter here, name, refers to the Data Entity's acronym (for example, CL for the Client's Data Entity) and it's the same for the next HTTP requests.

The second parameter, where allows us to define the filter to use while requesting the documents from the Master Data. For example, email=johndoe@example.com.

Finally, fields is there to specify what attributes we want to retrieve from the results.

Here's an example to retrieve the first name and last name from a client knowing its email address.

getFromMasterData('CL', 'email=johndoe@example.com', 'firstName,lastName')

POST

function postInMasterData(name, email, fields) {
    var store = 'storeName';
    var urlProtocol = window.location.protocol;
    var apiUrl = urlProtocol + '//api.vtexcrm.com.br/' + store + '/dataentities/' + name + '/documents';
    var response;

    var who = {
        "email": email
    };

    var data = $.extend(who, fields);

    $.ajax({
        "headers": {
            "Accept": "application/vnd.vtex.ds.v10+json",
            "Content-Type": "application/json"
        },
        "url": apiUrl,
        "async" : false,
        "crossDomain": true,
        "type": "POST",
        "data": JSON.stringify(data)
    }).success(function(data) {
        response = data;
    }).fail(function(data) {
        response = data;
    });
    
    return response;
}

In this case, email needs to be an actual email address that the code is going to use as an unique identifier of the document that is going to be created on the Master Data, and fields is a JSON object with the attributes and values to send in the request.

Life is better with examples.

var someAttributes = {
     firstName : 'John',
     lastName : 'Doe'
};

postInMasterData('CL', 'johndoe@example.com', someAttributes);

PATCH

function patchInMasterData(name, email, fields) {
    var store = 'storeName';
    var urlProtocol = window.location.protocol;
    var apiUrl = urlProtocol + '//api.vtexcrm.com.br/' + store + '/dataentities/' + name + '/documents';
    var response;

    var who = {
        "email": email
    };

    var data = $.extend(who, fields);

    $.ajax({
        "headers": {
            "Accept": "application/vnd.vtex.masterdata.v10+json",
            "Content-Type": "application/json"
        },
        "url": apiUrl,
        "async" : false,
        "crossDomain": true,
        "type": "PATCH",
        "data": JSON.stringify(data)
    }).success(function(data) {
        response = data;
    }).fail(function(data) {
        response = data;
    });
    
    return response;
}

The parameters here works just as the POST's example, where email is the way to identify the document is going to be edited and fields the JSON object with the attributes and values, as show in the following example.

var someAttributes = {
     firstName : 'John'
};

patchInMasterData('CL', 'johndoe@example.com', someAttributes);

PUT

function putInMasterData(name, email, fields) {
    var store = 'storeName';
    var urlProtocol = window.location.protocol;
    var apiUrl = urlProtocol + '//api.vtexcrm.com.br/' + store + '/dataentities/' + name + '/documents';
    var response;

    var who = {
        "email": email
    };

    var data = $.extend(who, fields);

    $.ajax({
        "headers": {
            "Accept": "application/vnd.vtex.masterdata.v10+json",
            "Content-Type": "application/json"
        },
        "url": apiUrl,
        "async" : false,
        "crossDomain": true,
        "type": "PUT",
        "data": JSON.stringify(data)
    }).success(function(data) {
        response = data;
    }).fail(function(data) {
        response = data;
    });
    
    return response;
}

More of the same, just like the last two codes. And a similar example.

var someAttributes = {
     lastName : 'Doe'
};

putInMasterData('CL', 'johndoe@example.com', someAttributes);

This is on GitHub

I decided to put this snippets on a Git repository you can find in https://github.com/nahuelsanchez/vtexmasterdataapiconnection.

Feel free to send any improvement you think this code desperately needs (thanks in advance).

Differences between POST, PATCH and PUT in VTEX Master Data

We can thrown five different HTTP requests at the VTEX Master Data: GET, POST, PATCH, PUTCH and DELETE. GET and DELETE are very simple to understand (once for get documents and the other one to delete them), but POST, PATCH and PUT seems like they all do the same thing.

There are small differences between POST, PATCH and PUT that justify the existence of all of them, and knowing this could improve our VTEX implementation and how we interact with the Master Data.

POST, PATCH or PUT?

The first one, POST, allows us to create a new document in a specific Data Entity. If the document already exists we won't be able to introduce the new data into the Data Entity.

For example, if we perform a POST request to create a new client with the email johndoe@example.com and name John, but the Data Entity CL already has a client with that email address a new document won't be created.

It doesn't matter if the existing document with the email johndoe@example.com has a different name for the client. Since the email needs to be unique the request will fail and the other attributes like the name will be discards.

On the other hand, PATCH works just like POST in terms that it will create a new document, but if the document already exists then the attributes from the existing document are updated with the new values that we are sending in the request.

Take into consideration that PATCH, in the scenario where the document already exists, will update only the attributes that we are sending in the request. The attributes that exists on the document but are not mentioned in the request won't be affected.

Finally, PUT works as POST too when the document doesn't exists: it creates a new one with the values we're sending in the request.

When using PUT in an scenario where the document already exists it will cause the existing document in the Data Entity to be completed overwritten. In other words, the existing document will be deleted, a new one will be created with the attributes mentioned in the request, and the ignored attributes in the request will be empty in the final created document.

POST, PATCH and PUT in VTEX Master Data documentation

Let me recap. POST to create a new document, PATCH to create a new document if it doesn't exist or to update the values of the attributes in an existing document, and finally PUT to create a new document if it doesn't exist or to overwrite an existing document.

A friendly example

Given an empty CL Data Entity, we perform a POST to create a new document with the following JSON in the request.

{
     email : "johndoe@example.com",
     firstName : "John",
     lastName : "Doo"
}

Since the document doesn't exist, it will be created.

Then, we decided to change the lastName of the document because we spot a typo on it. For this, we use PATCH and the following JSON in the request.

{
     email : "johndoe@example.com",
     lastName : "Doe"
}

After the request the document on the Data Entity will look like the following.

{
     email : "johndoe@example.com",
     firstName : "John",
     lastName : "Doe"
}

Finally, the document became obsolete and we need to overwrite it using PUT and the following JSON.

{
     email : "johndoe@example.com",
     firstName : "Jane"
}

The existing document with that email address will be deleted and a new one will be created, as follow.

{
     email : "johndoe@example.com",
     firstName : "Jane",
     lastName : ""
}

As you saw, lastName is empty.