Magento 2: Optimization with GraphQL
![developer is optimizing magento 2 with graphql](http://dev.global4net.com/wp-content/uploads/2021/06/magento2-graphql-optimization-1.jpeg)
If we were to learn something from the IT industry, it would certainly be the fact that everything can be optimized. Surely, it won’t always be a big change, however, your solution is going to be better. IT shows that progress is not rapid and sudden. During majority of the time, the process of advancement is slow but steady and unyielding. It is especially true for the e-Commerce platform optimization and we’ll be talking about one of the most popular of them – Magento. After reading this article you will have known how to start optimization in Magento 2 using GraphQL.
How can you optimize server-client communication in Magento 2 with GraphQL?
Magento 2 is an e-Commerce platform used by professionalists all around the world for online store building and maintenance. As the saying goes, “the customer is always right”. So, if the e-customer wants speed, the e-Commerce owners have to maximally optimize their sites so they provide the fastest and most comfortable experience. It’s right here that the GraphQL technology enters. But how does it work and how can it optimize site communication in Magento 2?
What is GraphQL?
GraphQL is an open source query language for API systems. It was created by Facebook back in 2012, but today it is supported by GraphQL Foundation. The foundation was established by Facebook owners in order to further advance the GraphQL on the non-profit basis. As a result of this, a growing community of developers has picked interest in the query language. Today it is one of the more popular ones. It contains numerous libraries that allows other platforms to utilize GraphQL, both on the backend and on the fronted. Two of the GraphQL libraries are included in the Magento 2 tech stack: webonyx/graphql-php (server-side) and Apollo Graphql Nano (client-side).
How does GraphQL work?
GraphQL uses queries to efficiently and flexibly obtain data and information needed for responses to website users actions. The system sends requests in protocol HTTP and HTTPS. In return, it receives responses written in JSON format – a language based on JavaScript, created for intersystem data exchange. However, before the query is sent you have to ensure that it is compatible with the predefined schema on the server. Additionally, in GraphQL the properties of data downloaded from backend depend on the type of request:
- POST queries are sent to the body
- GET queries are sent in form of parameter
We’ve written about how does the frontend-to-backend communication works in a previous article. However, in order to better understand what is GraphQL responsible for, we will shortly sum it up:
- A user conducts an action on the client-side, e.g. clicks on the product miniatures to enlarge it.
- This action generates request that is send to the server-side.
- The server utilizes language, analyzes the request and defines what data will be send back to the client-side as a response.
- The data is sent to the client-side and downloaded by the user’s browser or app. As a result, the product miniature is enlarged.
Sounds simple? Maybe so, but it certainly is not. After all, it is not enough to make something right, but make it better than others. In the e-Commerce world “better” means faster and more comfortable for the user. How does exactly GraphQL stand out from the other APIs? What makes it better for Magento store optimization?
Magento 2 optimization: GraphQL vs REST API
Both technologies share some similarities when it comes to fulfilling queries. Like GraphQL, REST also uses HTTP/S protocols to communicate with backend and sends responses in JSON format. Both languages also define the data obtained from backend as resources. For example, e-Commerce platforms like Magento, resources can be products, users, categories, prices, etc. Although, both languages use resources, GraphQL does it differently than REST.
Differences in fulfilling resource queries
REST API assigns every single resource to a different endpoint (which is one end of the frontend-backend communication channel). It means that when you use REST the system will have to send your requests to different endpoints depending on their type.
On the other hand, GraphQL sends all its queries to one shared endpoint. What are the effects of it?
REST API doesn’t give you control over how much data you want to obtain from the resource. When you send out the resources query to the given endpoint, you’ll have to download all the data that stored in it. That’s because the REST methods have predefined interfaces, which forces the responses from server-side to contain all field defined in the given interface.
On the contrary, GraphQL offers more flexible and effective solution to that problem. When using this query language, you can actually define what data are going to be retrieved from the backend. You are able to do this after making changes to the request’s structure. You don’t need an extra endpoint for specific resources. It suffices that you define your query type (GET or POST) to show the API what data you need. What’s more, you can further configure GraphQL queries to better scale data and optimize backend-frontend cooperation in your Magento store.
GraphQL lowers query amount
Too high amount of queries sent to backend is not good for the store optimization. REST API forces you to send more queries when you want to define more specifically what type of data you need; one query regarding resources, second regarding the data stored within. Only after this prolonged procedure, the wanted data will be rendered on the client-side.
Query nesting
At the same time, GraphQL allows you to shorten this operation in two ways: query nesting and query linking. First let’s explain the query nesting. Simply put, it means locating two or more separate queries into one request. This nested query is composed of the main query and a subquery. The main query part defines what resource is the query sent to, while the subquery tells what data is to be retrieved.
Recursive queries
This method can be further enhanced with the help of recursive queries. This type of queries allows for nesting multiple main and subqueries in one query. In effect you can retrieve whole sets of data with just one request. This greatly shortens the work time of developers and lowers the chance of making error when building site architecture. Additionally, utilization of recursive queries works for the users’ benefits. When you base your site on this type of queries, the data retrieved from the backend is saved in cache memory. Therefore, the user does not have to wait for the queries to be send and for the data to be saved. Additionally, they can now access the store when offline.
Query linking
The second method of lowering query amount is query linking. This operation is especially helpful when your app or site requires downloading data about elements and settings whenever user enters the store. Some platforms like Magento have predefined query for this type of operation. Thanks to GraphQL you can further optimize client-to-server communication. Instead of sending out two requests for data to be cached, you can put them in one request. Thus you can link queries that regard completely unrelated backend resources and cache them afterwards. This will speed up the functioning of the whole page and make it easier for developers to work with it.
GraphQL query fulfilling in Magento 2
Magento 2 has defined a special area for the GraphQL query processing. This enabled configuration of suitable rules of Dependency Injection for this query language. The rules include configuration of queries and their schemas, which takes place in the schemaGraphQL file. When it comes to the logic, you will have to prepare the data by creating a specific class, which will define the right interface.
Apart from the area dedicated for GraphQL queries, Magento 2 also allows for request caching for this language. This is done with the frontend library Apollo GraphQL. Before using this tool, it’s worth knowing how to configure query caching settings.
Query caching in Magento 2 with Apollo GraphQL
You must remember that caching in Magento works only when the fullpageCache option is turned on. Additionally, only the GET queries are cached, while the default query type sent by Apollo GQ is POST. That’s why the first change you’ll make should be changing the type of default requests. After that you can start optimizing query processing in Magento 2 by using the many functions and tools the Apollo GraphQL offers:
- InMemoryCache
- Cache managing – Fetch Policy
- persistCache library
- Middleware defining for GraphQL requests
InMemoryCache
This component lets you save the data in the browser window that has been downloaded from the server before. Thanks to that, the user returning to the site does not have to wait for the queries to be sent to the backend. Instead, the data is rendered instantly. Additionally, this tool allows you to cache whole requests and specific objects. What’s more, you can define cache key for each and every object.
Cache managing with Fetch Policy
With this tool you can define the type of caching policy for every query type. Already at the beginning, you have access to a few of predefined policy schemas:
- cache-first – default cache policy in Apollo. This setting focuses more on fast response time than on retrieving the most up-to-date data.
- cache-and-network – this policy attempts to balance fast response time and in-cache data updates.
- network-only – the point of this cache policy is to focus on updating the dating and caching the most up-to-date information, while saving on query response time.
- cache-only – this policy saves the data without updating it.
- no-cache – similar to network-only policy. It searches and retrieves the most up-to-date data, however it does not update it itself.
All the data concerning the caching policies is stored in cache storage. However, after refreshing or reopening the site you’ll have to download it once again.
persistCache library
Apollo GraphQL’s persistCache allows for dynamic content transfer between InMemoryCache to localstorage module. What’s more when the site is reopened the data is transferred again from the module to the InMemoryCache as initial state cache.
Middleware defining for GraphQL requests
GraphQL equips you with option of defining which middleware (software that lets two separate application or systems communicate with each other) is going to be responsible for request authorization. This can be especially helpful when you encounter problems with your website loading. In this case, instead of showing an error notification, you can configure the middleware to forcefully repeat the request loading, while the app is showing the user the loading page.
You also have to remember that to gain the access to Apollo GraphQL, you’ll have to configure Magento PWA Studio. This will allow for further optimization of GraphQL queries and server-to-client communication in Magento 2.
Magento 2 optimization: Advantages of GraphQL
When comparing the two technologies that are GraphQL and REST, you can see certain advantages on the part of GraphQL:
- By dividing queries into types, the amount of data that user has to retrieve when browsing your store decreases.
- lower amount of endpoints and requests sent to backend relieves the database.
- increased control over the type and amount of retrieved data and requests.
- thanks to the query nesting and linking the time of development is shortened. Additionally, the server-to-client communication speed is increased.
- Magento allows for request and schema defining, which can optimize the server’s logic to your needs.
- By using Apollo GraphQL you are able to set request cache rules, optimize data interchange and increase the website efficiency.
As you can see GraphQL offers more flexible and effective solutions of app optimization for Magento 2. Just like the platform from Adobe draws hundreds of thousand businesses with its abilities of in-depth enhancement and personalization, so does GraphQL with its numerous ways of communication refinement and optimization strategies. Only thing that you need to do is to find a way for it to help you in your business.