Kinsta® https://kinsta.com/ Fast, secure, premium hosting solutions Mon, 09 Dec 2024 13:49:28 +0000 en-US hourly 1 https://wordpress.org/?v=6.1.7 https://kinsta.com/wp-content/uploads/2024/09/cropped-Kinsta-black-favicon-1-32x32.png Kinsta® https://kinsta.com/ 32 32 Reverse proxies can be complicated (but not at Kinsta) https://kinsta.com/blog/reverse-proxies/ https://kinsta.com/blog/reverse-proxies/#respond Thu, 05 Dec 2024 03:19:02 +0000 https://kinsta.com/?p=187284 Creating a website reverse proxy might seem like a straightforward task that any experienced WordPress developer or business owner with some tech-savvy can handle. With tons ...

The post Reverse proxies can be complicated (but not at Kinsta) appeared first on Kinsta®.

]]>
Creating a website reverse proxy might seem like a straightforward task that any experienced WordPress developer or business owner with some tech-savvy can handle. With tons of tutorials and open-source tools available online, it’s easy to underestimate the complexities involved. But configuring a reverse proxy is often more complicated than it appears — especially for businesses looking to scale.

Reverse proxies are gateways between clients and servers and perform essential functions like load balancing, SSL termination, caching, and unifying multiple origin servers under a single hostname. These features help websites run smoothly, securely, and efficiently. But unless you have a team of experts, managing reverse proxies can be complicated.

What is a reverse proxy? A quick primer

Proxy servers support a wide variety of tasks as intermediaries in Internet communication and can generally be defined as forward proxies or reverse proxies. Forward proxies mask what’s happening on the client side (think of a server fulfilling web browser requests for staff at a corporate office), while reverse proxies mediate requests to one or more servers — origin servers — that host web content or application services.

Reverse proxies can serve multiple important functions, including:

  • Load balancing: When distributing incoming traffic across several servers, reverse proxies can ensure no single server is overwhelmed. This boosts performance and reliability, especially for high-traffic websites.
  • SSL termination: Reverse proxies can manage SSL/TLS encryption, offloading the heavy lifting of decrypting secure connections from backend servers. This simplifies backend server configurations and improves site performance.
  • Caching: Reverse proxies store copies of frequently requested data and serve it directly to users without having to reach the backend server each time. The Kinsta CDN and Edge Caching are forms of reverse proxy.
  • Site performance and security improvements: Reverse proxies can also act as gatekeepers, blocking malicious requests and filtering out harmful traffic before it reaches the origin servers.

These functions are critical for many types of customers — from e-commerce businesses to agencies managing multiple client sites. They help websites run smoothly, securely, and without performance bottlenecks.

However, configuring a reverse proxy for Web servers like Apache and NGINX requires significant expertise and attention to detail — especially when it comes to custom setups or high-demand environments. Without deep knowledge of how these systems work, it’s easy to misconfigure something, leading to performance issues or security vulnerabilities.

Why reverse proxy configuration is hard to do manually

Even for experienced developers, setting up and maintaining a reverse proxy manually is a lot of work. Here are some of the main difficulties that arise when setting up a reverse proxy manually:

Complex configurations

Reverse proxies aren’t a one-size-fits-all solution. Depending on your needs — whether you’re handling multiple domains, balancing traffic across servers, or dealing with SSL certificates — each configuration must be customized to your specific environment. With tools like Apache or NGINX, even small errors in configuration files can lead to performance issues, downtime, or worse, leaving your site vulnerable to attacks.

Multi-server setups

Managing reverse proxies across several servers adds another layer of complexity. As your business scales, you may need to update configurations to handle growing traffic, optimize performance, or adjust security rules. Keeping these configurations synchronized across multiple servers takes a lot of time and is also prone to errors.

Security vulnerabilities

Reverse proxies can filter out malicious traffic, but misconfigurations can open the door to vulnerabilities. Inadequate SSL termination, incorrect firewall rules, or improper caching could expose your website to threats like data breaches, DDoS attacks, or man-in-the-middle exploits. To prevent this, you need to stay up to date with the latest security patches and protocols to ensure the configurations remain secure. That’s an ongoing commitment that takes time and expertise — and not everyone has the time or capability to devote to that.

Ongoing maintenance

Once a reverse proxy is up and running, the work doesn’t stop. You’ll need to regularly update configurations, apply security patches, optimize settings for performance, and monitor for any potential issues. If your setup involves custom configurations, this maintenance can become even more resource-intensive, especially if issues arise that require troubleshooting.

For many businesses managing multiple sites for clients, this ongoing management could consume a lot of resources. The time spent configuring, updating, and securing reverse proxies is time not spent focusing on core business activities or delivering value to clients.

Kinsta simplifies reverse proxies for agencies

Managing reverse proxies manually is a headache, especially for businesses that need to maintain high-quality service while juggling multiple client projects. Thankfully, Kinsta’s expert team can step in to take care of the complex setup and ongoing maintenance. This means your business (and your clients) benefit from all the advantages of reverse proxies — without the technical stress.

With Kinsta, you don’t have to worry about:

  • Configuration: Kinsta’s team of experts handles the entire reverse proxy setup for you. Whether you’re dealing with complex, multi-server environments or unique client requirements, Kinsta’s managed service ensures everything is configured correctly the first time.
  • Ongoing maintenance and updates: From applying security patches to optimizing for better performance, Kinsta continuously monitors and maintains your reverse proxy.
  • Scalability: As your business grows and the needs of your clients evolve, reverse proxy configurations often need to be adjusted to accommodate higher traffic, additional servers, or more complex environments.

This makes Kinsta’s reverse proxy solution particularly beneficial for companies that want to offer a premium service to their clients. Instead of spending valuable hours managing reverse proxies, you can pass on the setup and management costs to clients while offering a more robust and reliable infrastructure.

For agencies without a dedicated IT or development team, Kinsta’s reverse proxy service provides peace of mind. Even if you don’t have the technical know-how, Kinsta ensures that your sites are optimized for speed, security, and scalability — without any heavy lifting on your end.

Advantages of Kinsta’s reverse proxy setup vs free solutions

When comparing Kinsta’s reverse proxy service to free options, the differences are stark. While free tools may initially seem cost-effective, the hidden costs in terms of time, expertise, and ongoing maintenance often outweigh the benefits. Kinsta offers a hassle-free alternative that makes it easier to scale, secure, and optimize your sites.

Here are the key advantages of Kinsta’s reverse proxy setup over do-it-yourself options:

No DIY headaches

With free tools, you’re responsible for everything, from the initial configuration to ongoing maintenance. Configuring NGINX or Apache as reverse proxies or turning to a third-party service might sound simple on paper, but real-world deployments often require hours of tweaking, troubleshooting, and adjusting. On top of that, you have to stay on top of security updates and performance optimizations yourself. Kinsta eliminates all of these hassles by doing the hard work for you.

Cost-effectiveness for businesses

Companies can benefit from incorporating Kinsta’s Reverse Proxy Add-on into their client packages. You can access this within the MyKinsta dashboard. The $50/month cost is easily justifiable as a managed service, offering clients peace of mind that their website infrastructure is being handled by professionals.

Screenshot showing the Reverse Proxy Add-on option in MyKinsta.
Accessing the Reverse Proxy Add-on in MyKinsta.

This also frees up larger businesses and agencies to focus on higher-value tasks like bringing in new clients or improving service offerings instead of getting bogged down by technical details.

Optimized for speed and security

Kinsta optimizes reverse proxies for performance and security right out of the box. This includes handling SSL certificates, caching, and load balancing — critical features that require specialized knowledge when configuring with free tools. With Kinsta, these optimizations are baked into the service, so you don’t have to worry about whether your proxy is running at peak efficiency.

Built-in scalability

One of the biggest challenges with free reverse proxy solutions is scaling. As your traffic grows, you’ll need to continually adjust settings to handle the load, which can be a nightmare if you don’t know what you’re doing. Kinsta’s managed service is designed to scale with your business. Whether your traffic spikes due to a viral campaign or gradual growth, the infrastructure can handle it without you needing to do anything.

Proactive support

Perhaps the most significant advantage of Kinsta’s reverse proxy service is our proactive support team. Unlike free tools that leave you on your own when troubleshooting, Kinsta’s expert team monitors and maintains your setup, ensuring any issues are resolved before they impact you or your clients.

Summary

Setting up and maintaining a reverse proxy doesn’t have to be a complicated, time-consuming task. If you opt for Kinsta, all the configuration, maintenance, and optimization is handled for you, allowing you to focus on what matters most: growing your business and delivering value to your customers.

If you’re tired of the hassle that comes with free reverse proxy tools, or if you simply want peace of mind knowing your reverse proxy is set up and maintained by professionals, Kinsta can help. Whether you’re managing a single site or hundreds, Kinsta’s expert team ensures your infrastructure is always performing at its best.

Are you ready to simplify your reverse proxy setup? Try Kinsta today, use the Reverse Proxy Add-on, and see how easy it is to get started.

The post Reverse proxies can be complicated (but not at Kinsta) appeared first on Kinsta®.

]]>
https://kinsta.com/blog/reverse-proxies/feed/ 0
The complete guide to managing a WordPress multisite network https://kinsta.com/blog/multisite-management/ https://kinsta.com/blog/multisite-management/#respond Tue, 03 Dec 2024 15:00:33 +0000 https://kinsta.com/?p=188243 If a typical WordPress site is like a single storefront, a WordPress multisite network is an entire shopping complex: each site operates as an independent entity ...

The post The complete guide to managing a WordPress multisite network appeared first on Kinsta®.

]]>
If a typical WordPress site is like a single storefront, a WordPress multisite network is an entire shopping complex: each site operates as an independent entity yet benefits from centralized management and shared resources. WordPress multisite network management can be a headache unless you have a solid hosting infrastructure as the foundation.

This article explores how to maximize your WordPress multisite network management using Kinsta. And we connect this to practical, real-world scenarios that demonstrate when and how to implement various solutions. There’s a lot to cover, so let’s begin by understanding why multisite might make sense for your projects.

Getting started with WordPress multisite

The transition from standard WordPress to a multisite network can transform how you manage your web presence. While a regular WordPress installation will focus on the maintenance of a single site, multisite lets you manage an entire ecosystem of interconnected websites.

This fundamental difference impacts your development workflow, resource management approach, and much more. Understanding these differences becomes crucial when you plan your network’s architecture.

Each standard WordPress site maintains its own database tables, plugin configurations, and user base. In contrast, multisite shares these resources across the network — although you can still maintain individual site independence where it matters most.

Understanding Kinsta’s multisite architecture

Multisite installations at Kinsta benefit from infrastructure optimized for WordPress and built on the Google Cloud’s fastest servers and its premium tier network.

A system architecture diagram showing a hosting setup on the Google Cloud Platform. The flow starts with multiple user icons connected to Cloudflare. It connects to a Google Cloud Compute Engine LXD Host. This branches into two LXC Containers, and each has three icons to its right indicating it uses NGINX, PHP FPM, and MariaDB. Above and below the containers are ZFS Snapshot sections and an orange plus icon. Below the Compute Engine is a Premium Tier Network label.
Kinsta’s hosting infrastructure, incorporating Cloudflare and Google Cloud.

Kinsta’s isolated container technology means your network of sites operates within its own environment rather than sharing resources with the websites of other customers. In addition to the Google Cloud, Kinsta’s platform has Cloudflare on hand for optional CDN and edge-caching support.

When multisite makes sense (and when it doesn’t)

On the surface, choosing between a standard WordPress installation and multisite can be simple.

For example, if your agency manages multiple client sites that share similar configurations and requirements, WordPress multisite will help streamline your workflow. Educational institutions often benefit from this setup as it lets them maintain consistent branding across campuses and departments while providing autonomy. Franchise businesses can see similar benefits.

However, multisite isn’t always going to be an optimal solution. If your sites require different PHP versions or have conflicting plugin requirements, managing them separately makes more sense. Similarly, if each site has independent scaling needs or requires complex configuration customizations, individual installations will serve you better.

The key lies in looking at your specific use case with care and assessing your needs. Consider factors such as resource sharing, maintenance requirements, and scaling needs.

Setting up WordPress multisite network on Kinsta

You need to do more than toggle settings when it comes to setting up a WordPress multisite network, although the process doesn’t have to be complex and lengthy. It does require some thought and consideration of your network’s structure.

The process begins in the MyKinsta dashboard when you add a new site:

The Add Site form within the MyKinsta dashboard, showing several input fields including an admin username, password (obfuscated with dots), and email address. Below these fields is a language selector defaulted to English (US) and a series of checkboxes for optional features. The Install WordPress multisite option is highlighted in purple.
Adding a new WordPress multisite instance using the MyKinsta dashboard.

Once you toggle the checkbox to enable multisite, you will need to choose your network’s structure. Kinsta supports both subdomain and subfolder configurations, each with distinct advantages:

  • Subdomain setups (such as site1.example.com) work better for larger networks where each site needs its own distinct identity.
  • Subfolder configurations (such as example.com/site1) offer simpler management and suit smaller networks better.
The Kinsta dialog for setting up a new WordPress multisite instance. It shows a language selection interface with English (US) as the chosen option, followed by WordPress multisite installation options. The interface includes a radio button selection between Subdirectory and Subdomain installation types, with Subdirectory selected.
Choosing to use subdomains or subdirectories when setting up WordPress multisite.

After you click Continue and Kinsta completes the installation, you can start work on domain management.

Domain configuration and management

Domain management in a multisite network can require careful attention, but the MyKinsta dashboard simplifies the process.

The MyKinsta dashboard's domain management interface displaying the primary domain settings and domain list. The interface includes a search bar for domains, domain status indicators, and an Add domain button. The primary domain section explains that DNS records must be configured correctly, with options to open the URL or WordPress admin. The domain list shows a .kinsta.cloud domain marked as primary.
Managing domains within the MyKinsta dashboard.

External domain mapping deserves special attention because it lets you use different (and custom) domain names for each site in your network. This is something an agency would find valuable, given the need to manage multiple client sites. It might also be suitable for a company that maintains distinct brand identities across various products or services.

Kinsta handles the technical aspects of external domain mapping under the hood, and all you need to do is implement the custom domain name for each site. You also don’t need to worry about SSL certificate management or the intricacies of domain verification, which makes this step straightforward.

The MyKinsta dashboard displaying a modal window for adding a new domain. The interface includes a text field for entering a domain name (showing example.com as a placeholder), along with options for wildcard domain setup and SSL certificate configuration. The interface indicates that DNS verification is required and may take up to 24 hours to propagate.
Mapping domains within a WordPress multisite installation.

This part of the job has two steps:

  1. First, map domains within your WordPress multisite dashboard through the Sites > Edit link. Change the Site Address (URL) field to that of your custom domain.
  2. Within the MyKinsta dashboard, head to the Domains screen for your main multisite installation. Here, click the Add domain button, fill in the fields, and confirm the changes.

You will also update your DNS records to verify your domain. The last step is to head to the Tools tab within MyKinsta and open the Force HTTPS dialog. You don’t want to force all traffic to your primary domain, as you won’t have access to your network of sites. Instead, choose Force HTTPS on all your live domains and click the Force HTTPS button.

Implementing an NGINX reverse proxy

Kinsta’s NGINX reverse proxy capabilities add another layer of flexibility to your WordPress multisite setup. This feature becomes particularly valuable when you need custom routing rules or want to implement advanced load-balancing strategies. The reverse proxy lets you achieve a few tasks:

  • Directing traffic efficiently between different parts of your network.
  • Supporting custom caching rules for specific sections.
  • Handling SSL termination “at the edge.”
  • Managing complex routing scenarios.

For WordPress multisite networks, a reverse proxy is how you will serve multiple sites from a single domain. Consider a subsite that uses an example.kinsta.cloud subdomain. You can implement the reverse proxy to map this URL to mysite.com/example (or other variations).

A reverse proxy is not a core feature of Kinsta. Instead, you can purchase a dedicated Add-on to support it.

The Add-ons panel within the MyKinsta dashboard showing three available services: a PHP memory upgrade, reverse proxy service, and Redis caching. Each service includes a brief description and pricing information.
The Reverse Proxy add-on dialog within the MyKinsta dashboard.

Once you complete the whole setup and domain mapping process, you can begin to optimize and refine the performance of your WordPress multisite network.

Optimizing your multisite performance

Performance optimization is an aspect that is even more crucial for WordPress multisite network management. Issues can affect multiple sites simultaneously, which can impact engagement for other sites within the network that don’t stand in the direct line of fire.

Fortunately, Kinsta provides comprehensive tools to maintain this optimal performance across your entire network.

The power of Kinsta’s caching stack

Kinsta implements a sophisticated caching system that both WordPress multisite and single sites can access. There are four main ways to cache a site:

  • Server (or local) page caching
  • Edge caching
  • Redis caching
  • A cache for the built-in content delivery network (CDN)

You can access each of these caches through the MyKinsta dashboard. The system operates at multiple levels, with individual configurations available for each subsite within the network. It also means you don’t need additional third-party plugins to cache your site.

This holistic caching begins at the server with a typical implementation and an option within the dashboard to clear the cache. WordPress websites can leverage dedicated caching for the platform that includes bytecode caching using the native OPcache extension for PHP.

Edge caching takes this a step further with global distribution. Once a visitor requests a page, edge caching serves it from the nearest server location thanks to Cloudflare. Within the MyKinsta dashboard, you have options to clear the mobile cache, the entire cached dataset across every location, and the same for an individual URL you enter.

The Caching configuration page of the MyKinsta dashboard showing Edge Caching settings. This is enabled with options for mobile cache creation and cache clearing functions. The interface includes buttons to disable caching and clear specific URL caches, with a note that clearing can take up to five minutes.
The edge caching options within the MyKinsta dashboard.

This system is particularly valuable for multisite networks serving visitors from different geographical regions. Edge caching combines well with Kinsta’s typical CDN cache to handle static assets such as images, CSS, and JavaScript files. With 260+ Cloudflare PoPs worldwide, you can ensure fast loading times regardless of visitor location.

Within MyKinsta, you can clear the cache, tweak image optimization, and set up exclusion rules.

The Kinsta CDN configuration page within the MyKinsta dashboard showing three main sections: CDN status, cache management with a Clear CDN cache button, and image optimization settings that can convert images to WebP format. The interface also includes options to exclude specific files from CDN caching.
The CDN caching options within the MyKinsta dashboard.

While Kinsta provides database object caching functionality as standard, Redis caching enables you to store the values the object cache generates. This is also an option found in MyKinsta’s Add-ons section.

Leveraging the Application Performance Monitoring tool

Performance testing will be a pivotal part of your WordPress multisite network management. Given that you have potentially hundreds of sites to manage, it’s important to have a quick and accurate way to assess your network’s and individual sites’ performance.

Kinsta’s Application Performance Monitoring (APM) Tool monitors PHP processes, database queries, and AJAX calls to help you identify and resolve bottlenecks before they impact your users.

The Kinsta APM Tool interface showing WordPress performance metrics with monitoring enabled for a set period. The dashboard presents the Slowest WordPress plugins and Slowest WordPress hooks tables.
The Kinsta APM Tool.

While there are plenty of performance tools on the market, you can access key metrics of the APM tool directly within the MyKinsta dashboard. You can monitor various aspects of your sites, such as database queries, slow WordPress hooks and plugins, and receive breakdowns of transactional requests — key for speeding up your site.

The Slowest transactions panel from the MyKinsta dashboard. It shows metrics for the /wp-cron.php file. The table details Total Duration, Max Duration, Average Duration, and Rate Per Minute, with explanatory text about transactions being page views or background jobs.
The MyKinsta dashboard showing slow transactional requests for a WordPress website.

The APM Tool excels at identifying slow database queries. This is important for WordPress multisite networks, where many sites will share database resources. It helps you optimize these queries and improve overall network performance.

Every site can benefit from the APM Tool. For instance, WooCommerce stores could monitor checkout speed through the impact of API requests. The APM Tool is also great for identifying sluggish site speed at certain times of the day.

Photography tutorial website PHLEARN has big traffic numbers and uses Kinsta’s monitoring to ensure its site loads well for all of its site’s members. Of course, potential new signups will benefit from the improvement of the user experience (UX), too.

How Kinsta helps secure your WordPress multisite network

Security takes on added importance when it comes to WordPress multisite network management. A security breach could potentially affect many sites within the network.

Kinsta employs industry-leading and state-of-the-art security technology to keep your sites safe at the server level.

Leveraging Kinsta’s security infrastructure

Kinsta’s approach to security is SOC 2 compliant and ISO 27001 certified. Adherence to these industry-standards demonstrates Kinsta’s commitment to maintaining rigorous security protocols:

  • SOC 2 compliance. This proves that Kinsta adheres to several trust services criteria, and is a marker for user safety.
  • ISO 27001 certification. This is the “gold-standard” for confidentiality, integrity, and availability of information and data on Kinsta’s servers.
The Kinsta Trust Center page. It displays a compliance and controls dashboard showing various security certifications including ISO 27001:2022, ISO 27017, ISO 27018, SOC 2 Type II, CSA STAR Level 1, GDPR, and CCPA. The controls section features four main categories: Infrastructure security, Organizational security, Product security, and Data and privacy, each with specific implemented controls such as database authentication, encryption, and data retention procedures. A timestamp indicates the dashboard was updated a minute ago.
Learn more about security standards compliance in the Kinsta Trust Center.

Your sites also benefit from Cloudflare’s security functionality to combat malicious intent. This includes enterprise-grade distributed denial of service (DDoS) protection, a web application firewall (WAF), bot protection, and more.

Between the baked-in protections from the Google Cloud Network, Kinsta’s trust markers, and Cloudflare’s top-class provision, you have almost all of the answers to questions relating to your network’s security.

Monitoring and maintenance

Alongside the APM Tool, you have other ways to make sure no sites on your WordPress multisite network fail. For instance, Kinsta monitors the uptime of your network every three minutes. If there’s a drop in uptime, you receive an email notification:

An error notification message from Kinsta explaining that site assets are not working properly. The message includes instructions to check the log viewer for errors with a promise to re-check the site in six hours. It ends with a friendly note offering 'around-the-clock' support chat assistance. The text is presented on a white card with a professional, clean layout and redacted sensitive information.
An email notification telling a site owner about low uptime metrics.

You may find your network analytics within the MyKinsta dashboard can help you spot potential issues alongside the built-in logging functionality:

The Analytics panel within the MyKinsta dashboard displaying two main sections: Top countries and Top cities with their respective request counts.
Kinsta’s analytics screen within the MyKinsta dashboard.

What’s more, there are dedicated tools to log user activity within MyKinsta:

The User Activity logging interface within the MyKinsta dashboard. It shows recent actions by multiple users. The log displays three entries for enabling APM on site, enabling strip cookies, and creating a site at. Each entry includes a user identifier, action description, timestamp, and green checkmark status indicator.
The User Activity screen within the MyKinsta dashboard.

Other tools available within MyKinsta to protect your multisite network include IP Deny, which works at the network level to block traffic from malicious IP addresses:

The Kinsta IP Deny configuration interface with an Add IP addresses to deny modal window. The modal includes example IP formats and provides a text area for entering multiple IP addresses on separate lines. The window has Cancel and Add IP addresses buttons at the bottom.
The IP Deny tool within the MyKinsta dashboard.

Finally, through a network-wide plugin such as Wordfence, you can also implement routine malware scans (and removals), which is a benefit of being able to use WordPress plugins across your entire multisite network.

WordPress multisite network management: development and deployment

An efficient development and deployment workflow will be essential for WordPress multisite network management. Kinsta provides a “local-to-live” workflow that begins with DevKinsta as your local development environment:

The DevKinsta home page logo showing a dark blue monochromatic illustration with hands reaching toward a computer monitor displaying the letter
The DevKinsta logo.

Using DevKinsta, you can mirror your production setup on your local machine, make the changes you need, and then push them back to your online servers. For multisite, DevKinsta can pull a network instance from your server through its import dialog:

The DevKinsta dark interface for creating a new site. It presents three options against a dark background: New WordPress site, Import from Kinsta, and Custom site. Each option is represented by a blue and white geometric pattern with an icon.
Importing a WordPress multisite instance from MyKinsta to a local DevKinsta environment.

This will let you set your multisite directory structure before the import takes place:

The DevKinsta WordPress site setup interface displaying key information such as the site's status, WordPress version, and PHP version. Below these details is a WordPress multisite configuration section with three options: No multisite, Subdomain, and Subdirectory. At the bottom are Cancel and Import site buttons. A warning message explains that multisite setup cannot be automatically detected.
Choosing a WordPress multisite directory structure within DevKinsta.

DevKinsta’s syncing functionality lets you push and pull to and from your server using a minimal number of clicks:

A portion of the DevKinsta interface displaying four action buttons: Open site, a Sync drop-down menu with Push to Kinsta and Pull from Kinsta options, Database manager, and WP Admin.
DevKinsta lets you push and pull between your local machine and a live server.

The important aspect of a multisite local-to-live pipeline is the My Sites dashboard within WordPress:

A WordPress multisite dashboard displaying
The My Sites dashboard within WordPress multisite.

Another crucial part of your local-to-live workflow is staging and testing your network’s changes.

Staging and testing strategies

Using a staging environment is a critical decision when working with WordPress multisite. There are a few approaches to building a staging site for your network, but Kinsta provides one-click staging within the MyKinsta dashboard:

The MyKinsta window to create a new environment. It presents two environment options: a Premium environment for resource-intensive sites, and a Standard environment for testing and development. The interface uses a clean design with white cards, green accents, and clear pricing information. Navigation options and site management tools are visible in the background sidebar.
Toggling staging within MyKinsta.

With premium staging, you could create many different copies of your setup, test your changes, and push the correct ones live. There are plenty of advanced ways to utilize staging for your WordPress multisite network management, including incorporating version control.

A common approach to deployment is to push changes to a GitHub, GitLab, or Bitbucket repo, with some server-side scripts fetching changes and updating the site. Multisite networks can benefit from both monorepo and multirepo setups, and a version control approach works for staging and live deployment.

Testing your network and changes will depend on your development goals. Individual site testing could be simple functionality checks or advanced unit testing.

Putting your workflow together: a summary

You will work with your local and staging environments for almost all of your development and deployment. Here’s a quick rundown of the steps we recommend:

  • If your network hub is already live, use DevKinsta to pull that instance to your local machine. Otherwise, you can create a new site either within MyKinsta and pull it to local, or directly within DevKinsta.
  • Within this local environment, make the changes you need. Version controlling those changes to a “feature” or “testing” branch is sound.
  • Part of this local process could involve some usability testing or other visual checks, although this will happen throughout your workflow.
  • It’s a subjective decision to push to staging through DevKinsta or your Git repo.

Once you have your network hub on a live server, you may want to set up an automated testing strategy and monitoring pipeline. This is also the right time to look at how your network will respond to scaling decisions.

How an agency can benefit from Kinsta’s WordPress multisite network management

WordPress agencies typically need custom and specific solutions for multisite network management. This is due to the custom workflows and cultures in each agency. For example, agencies might adopt different approaches to team collaboration.

User management

User management in MyKinsta includes the ability to invite other team members to the project:

MyKinsta's Users management interface showing an Invite users modal window. The modal lets you add up to ten email addresses and select user roles, with options for WordPress site administrator or WordPress site developer. The interface includes a close button and explains that the list contains users with service level access.
Inviting users to work on a WordPress multisite project within MyKinsta.

With many users working on your projects, it’s important to organize your access hierarchy and structure. You can set up various roles that offer access to the company as a whole or a particular service (such as database administration). Some of the lower-privilege options will be great for client access to the network or a specific site.

Analytics and reporting

Kinsta’s analytics are good for more than spotting traffic anomalies: it can also help you understand how that traffic hits your network and (by extension) your clients’ sites. Even a quick look at the Visits graph can tell you how much traffic in on the network throughout the day:

The Visits analytics graph within the MyKinsta dashboard shows 24-hour site traffic with unique IP address counts. The orange line graph displays several peaks and troughs, with major spikes at specific times. Time markers run from 16:00 to 15:00 the next day along the x-axis.
Monitoring site visits within the MyKinsta dashboard.

You can view basic resource usage for your network: disk space and bandwidth. Other tabs can give you an insight into PHP response times, memory limits, AJAX usage, error code breakdowns, and many more advanced metrics.

Analyzing your geographic data can have value in a number of ways. International clients or those who run multilingual sites will want to know where in the world its traffic comes from. MyKinsta can tell you this through the Geo and IP screen:

Kinsta's Analytics dashboard showing the Geo and IP panel. It displays visitor statistics with two main panels: Top countries and Top cities.
The Geo and IP analytics screen within MyKinsta.

For instance, if you notice significant traffic from a particular region, you might adjust your CDN configuration or consider using a closer data center. The information your site’s analytics gives you helps you to improve your service and your clients to better optimize their content delivery and server locations.

Site management

Kinsta provides a number of robust tools to help you manage the technical aspects of your WordPress multisite network. For example, it’s straightforward to change the PHP engine version your network uses:

The Tools page within the MyKinsta dashboard. It displays four main sections: ionCube Loader with an Enable button for encrypting PHP code, PHP engine showing version 8.1 is active with a Modify drop-down menu listing versions 8.1-8.3, Site Preview, and Early Hints sections. Each section has its own icon and explanatory text.
The PHP version changing tool within MyKinsta’s Tools screen.

You can use this in a few ways, such as testing the compatibility of different PHP versions during staging, monitoring those performance impacts, and processing (or rolling back) changes.

For performance monitoring, the APM Tool records your slowest database queries:

The Kinsta APM Tool dashboard showing a table of Slowest database queries. The detailed table shows various WordPress database operations. The table includes columns for query types, duration percentages, and timing metrics, with wp_sitemap SELECT query showing the highest total duration.
Monitoring a WordPress database using the APM Tool.

With any tools that change the fundamental settings of your WordPress multisite network, you should backup your site. Kinsta’s backups include a full snapshot of your multisite installation, including the database.

Migrating a database can be tricky to complete, especially with potential extra tables relating to networked sites. The Tools menu in the MyKinsta dashboard gives you a way to conduct a search-and-replace on your database:

The Search and replace tool within MyKinsta. The dialog window overlays the main interface, with fields to search WordPress databases. The search field contains wp_ and the replace field shows jgh05_. A checkbox for Clear cache when ready is selected, and the dialog includes a warning about automatic backups before making live environment changes.
Kinsta’s search and replace tool within MyKinsta.

You often have to change entries relating to domain names, table prefixes, and other elements that WordPress hard codes into the database.

Finally, your domain name system (DNS) management will need the best support possible — understandable given that you might run multiple sites with different domain names.

The MyKinsta DNS management interface. It presents a clean, dark-themed layout offering a premium DNS service. The page shows an empty state with an Add your first domain button and includes a helpful link about DNS basics in the relevant links section.
The Kinsta DNS management screen.

Kinsta offers robust DNS management, but premium DNS is not optional either in our opinion. We integrate with Amazon Route 53 to offer enterprise-grade reliability, global DNS propagation, advanced routing options, and more.

Summary

WordPress multisite network management requires careful planning and the right tools, but Kinsta can ease the burden through its rich architecture and infrastructure. For instance, you can build your development and deployment pipeline around DevKinsta and the built-in staging functionality. In addition, you have a wealth of monitoring and security options within the MyKinsta dashboard, including analytics and the APM tool.

What challenges are you facing with WordPress multisite network management? Share your experiences in the comments section below!

The post The complete guide to managing a WordPress multisite network appeared first on Kinsta®.

]]>
https://kinsta.com/blog/multisite-management/feed/ 0
Advanced WordPress development: how to build your next project with wp-scripts https://kinsta.com/blog/wp-scripts-development/ https://kinsta.com/blog/wp-scripts-development/#respond Thu, 28 Nov 2024 14:57:08 +0000 https://kinsta.com/?p=186948 WordPress development work for agencies can be competitive at the best of times. It requires supreme efficiency and consistency across multiple client projects. Regardless of how ...

The post Advanced WordPress development: how to build your next project with wp-scripts appeared first on Kinsta®.

]]>
WordPress development work for agencies can be competitive at the best of times. It requires supreme efficiency and consistency across multiple client projects.

Regardless of how seasoned you are as a developer, managing an entire portfolio of custom themes and plugins still needs perpetual effort when it comes to workflow streamlining. Enter wp-scripts: a powerful suite of utilities that can revolutionize how your agency approaches WordPress development.

This comprehensive guide looks at the capabilities of wp-scripts, and explores techniques for your build processes. Throughout, it will cover optimized compilation and bundling, automated linting, unit testing, and much more — all of it will speak to you if you juggle multiple high-stakes WordPress projects.

The concept of a ‘build process’

Before we look at the specifics of wp-scripts, let’s understand the broader concept of your web development build process. This consists of a series of automated tasks to help take your source code into a production-ready app or website.

For instance, there are many jobs that benefit from automation in this way:

  • Compiling modern JavaScript into browser-compatible code.
  • Transpiling CSS preprocessor languages (Sass, for example) into standard CSS.
  • Minifying and optimizing assets such as JavaScript, CSS, and media.
  • Running linters to catch potential errors and enforce coding standards.
  • Executing unit tests to ensure better code functionality.

These are good aspects to automate for any development workflow, but for agencies, the process is just as crucial. For starters, you can maintain consistency across multiple projects (and your team).

You can also develop and deploy through quicker cycles and maintain all of your projects by leveraging that consistency— even the most complex ones. For the end-user, the optimized performance you gain will trickle down to their overall experience.

Typically, your agency may ‘cobble together’ custom build processes using tools such as Gulp, Grunt, or even manual processes. However, these approaches can often lead to inconsistencies between projects, not to mention a significant maintenance overhead.

wp-scripts: a workflow-changer for WordPress development within an agency

In the context of WordPress, a build process can also offer significant streamlining for theme and plugin development. It lets you use modern tools and practices and ensure platform compatibility at the same time.

The @wordpress/scripts package — wp-scripts throughout this post — is a collection of configuration files and scripts that helps you simplify the build process for WordPress projects.

A code snippet displaying the scripts section of a package.json file for a WordPress project. It lists various npm scripts for tasks such as building, checking engines and licenses, formatting, linting (for CSS, JavaScript, Markdown docs, and package.json), updating packages, creating plugin zip files, starting the project, and running tests (both end-to-end and unit tests). All the scripts use wp-scripts as the base command.
Part of a wp-scripts reference for the various scripts a project will use.

The Make WordPress Core team develops and maintains the package, which is integral to the Block and Site Editors. Best of all, you can use it for custom theme and plugin development, too.

For approaching WordPress development at scale within an agency, wp-scripts will be a central part of the workflow. It’s more than a simple build tool; it’s a comprehensive solution for modern WordPress projects that aligns with the need for a sophisticated development workflow.

The key functionality of wp-scripts

As more modern JavaScript practices bleed into the WordPress ecosystem, we need more standardized build tools to accommodate them. A unified build toolset in the form of wp-scripts benefits the entire WordPress development ecosystem.

As such, wp-scripts offers a range of functionality that makes WordPress development more efficient:

  • ‘Zero-config’ setup. You can begin without the need for complex webpack configurations.
  • Modern JavaScript support. Your ES6 code will transpile for browser compatibility, and give you greater confidence in its accuracy.
  • Built-in CSS processing. If you use CSS preprocessors such as Sass, you get out of the box support.
  • Code quality tools. The package integrates both ESLint and Prettier for consistent code style and quality.
  • Testing utilities. You have Jest available within the package for unit testing and easy execution.
  • Hot reloading. If you have the ability to reload your changes live, this can speed up your development time.

Combined, wp-scripts offers many key advantages for agencies that manage multiple WordPress projects. For instance, you can standardize your development environment across every project and replicate the build process across any new projects, too. The package will let you centralize your build tool dependencies, which makes updates and security patches more manageable.

Overall, you can worry less about compatibility issues, reduce your setup time, and eradicate many of the typical errors you make throughout the less streamlined build process.

Comparing wp-scripts to a typical WordPress development process

Typical WordPress development often involves using manual enqueuing for scripts and styles. In addition, you’ll likely write vanilla JavaScript or jQuery, and rely on third-party build tools — or no build process at all.

In contrast, wp-scripts provides a modern, integrated approach in almost every area:

Element Typical development wp-scripts
JavaScript Often vanilla JavaScript or jQuery ES6 and React support
CSS Direct CSS or basic preprocessors Support for Sass and PostCSS processing
Build process A manual or custom setup using Gulp or Grunt Zero-configuration setup using webpack, integrated into the package.
Code quality Manual linting or separate tools integrated with your code editor ESLint and Prettier are built into wp-scripts
Unit testing If it’s not an overlooked step, there is usually a separate setup The package integrates Jest testing

On the whole, wp-scripts offers greater flexibility thanks to its integration with tools you may not already use. For example, the effort of setting up PostCSS, webpack, or Jest could be something you skip over due to time constraints.

How to set up your development environment to incorporate wp-scripts

Using wp-scripts has its own requirements, but you likely already use those tools. If you need to, install Node.js and npm along with a local WordPress development environment. DevKinsta will be a fine solution, thanks to running on Docker and supporting Kinsta’s staging environments.

The DevKinsta interface displaying site information for a WordPress website. It includes the site type, database type, webserver, and PHP version. The top of the interface shows buttons for Open site, Sync, Database manager, and WP Admin. A small preview of the website is shown on the left-hand side. The bottom of the interface has a Site status section with a Stop site button.

The main DevKinsta interface.

If you already use the create-block package to develop WordPress Block plugins, this installs wp-scripts alongside its other assets. From here, you can begin to set up a package development project.

Setting up a new WordPress project with wp-scripts

The work you undertake will be within the wp-content directory of your WordPress installation. The specific subdirectory will relate to the type of project you create: wp-content/themes for themes and wp-content/plugins for plugins!

Regardless, your project folder should include a number of files and directories:

  • A package.json file.
  • A build directory.
  • An src directory that also includes an index.js file.

To create a package.json file, navigate to your project directory using your Terminal or command line app. Running the npm init command will take you through an interactive setup process, and your ‘entry point’ should be build/index.js:

A terminal window with a dark background showing the output of an npm init command for a WordPress theme project. The text explains that this utility will guide the user through creating a package.json file, covering common items and suggesting sensible defaults. It provides instructions on how to install packages and save them as dependencies. The terminal shows the initial setup details, including the package name, version, description, and entry point.
A partial run through of the npm init process, showing the entry point value prompt.

Next, install wp-scripts as a development dependency:

npm install @wordpress/scripts --save-dev

You should see a couple of auto-generated directories and files, too: node_modules, and package-lock.json. Regardless, you now need to reference the predefined scripts within the package.json file:

"scripts": {
  "build": "wp-scripts build",
  "start": "wp-scripts start",
}

You will likely return to this file often to add further scripts as and when needed. For example:

…

"lint:js": "wp-scripts lint-js",
"lint:css": "wp-scripts lint-style",
"lint:pkg-json": "wp-scripts lint-pkg-json",
"test": "wp-scripts test-unit-js"
…

You may also need to enqueue your theme or plugin assets here and then save your changes.

Understanding and using webpack with wp-scripts

For bundling assets under the hood, wp-scripts uses webpack. You don’t need to configure this, although understanding its role can help you leverage wp-scripts in a more effective way. Webpack has a lot of responsibilities when it comes your setup:

  • It helps to resolve dependencies between your JavaScript modules.
  • You can transpile modern JavaScript to browser-compatible code.
  • It will help process and optimize your styles.
  • You’re able to generate source maps to debug easier.
  • It can help you create production-ready, minified bundles.

You have a default webpack configuration within wp-scripts already. This works well for most WordPress projects. In some cases, though, you might need to create custom configurations.

Advanced webpack configuration for agency setups

While the default webpack config is ideal for the majority of development projects, there are times when you need to create a configuration for your specific needs. For example, you may deal with complex theme structures or unique plugin architectures. This is where a webpack.config.js file in your project root will come in handy:

const defaultConfig = require("@wordpress/scripts/config/webpack.config");

const path = require('path');


module.exports = {
  ...defaultConfig,
  entry: {
    main: path.resolve(__dirname, 'src/js/main.js'),
    admin: path.resolve(__dirname, 'src/js/admin.js'),
    // Add more entry points as needed
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist'),
  },
  // Add custom loaders or plugins here
};

This configuration allows for multiple entry points, which is particularly useful for themes or plugins requiring separate scripts for different parts of the WordPress admin or frontend. As such, you can extend your default configuration and maintain the benefits of wp-scripts.

The basics of using wp-scripts

With a suitable development environment and the right file and folder structure in place, you can start to use wp-scripts. There are a few basic and core commands that will make up most of your time.

The start command watches your files for changes, recompiles assets on the fly, and provides hot reloading for a smoother development experience:

npm run start

You use this at the beginning of a project to start a development server, although it won’t optimize the compiled code within your build/index.js file.

When you need to deploy your project, the build command will compile your assets for production:

npm run build

Once you run this, it performs a few tasks. For example, it transpiles your JavaScript, compiles your Sass and SCSS to CSS, minifies all of your assets, and generates source maps. At the end, it will output everything to the build/index.js file. The build process also creates a build/index.asset.php file for cache busting.

The wp-scripts package also provides several linting commands to help you maintain high code quality:

  • npm run lint:js. You use this to lint your JavaScript files.
  • npm run lint:css. This lints your CSS or Sass files.
  • npm run lint:pkg-json. This validates your package.json file.

For unit testing, you simply call npm run test, which uses Jest to execute your test suite.

Exploring the core utilities in wp-scripts

Basic build tasks can take you a long time, and the typical commands will require a lot of automation. However, wp-scripts provides a suite of sophisticated utilities that will cater to the complex needs of your WordPress development:

  • Advanced compilation. With optimized configurations, you can transpile modern JavaScript — including ECMAScript Modules (ESM) and Javascript XML (JSX) — and compile Sass.
  • Intelligent bundling. You can leverage webpack’s code splitting and ‘tree shaking’ to optimize your asset delivery.
  • Comprehensive linting. You can enforce coding standards across JavaScript, CSS, and package.json files.
  • Integrated testing. With Jest, you can run unit tests and coverage reports.
  • Development server. You can utilize hot reloading for rapid development across multiple projects.

You can expand the default functionality of each to leverage a more customized WordPress development process, regardless of whether you work on themes or plugins.

Handling JSX and Modern JavaScript

Many WordPress projects work with modern JavaScript elements such as React components, arrow functions, destructuring, async/await, and more. Even aspects of the core codebase, such as the Block Editor, use modern JavaScript to build its functionality.

However, browsers don’t natively understand these advanced syntaxes, so more work is necessary to transpile and compile them.

JSX lets you write HTML-like code within your JavaScript, which makes it easier to describe what your interfaces and other elements should look like. This can improve readability and maintainability, for starters. You can also access powerful React components for creating dynamic user interfaces (UIs).

wp-scripts uses the Babel JavaScript compiler to transpile your modern JavaScript and JSX into code that browsers can understand. It handles all of the complex and necessary configuration, which lets you focus on writing code.

You leverage this through your src/index.js file. Check out this small example of how you might implement JSX and modern JavaScript using wp-scripts:

import { render } from '@wordpress/element';

// Modern JavaScript feature: Arrow function
const HelloWorld = () => {
    // Modern JavaScript feature: Template literal
    const greeting = `Hello, ${wp.data.select('core/editor').getCurrentPost().title}!`;    

    // JSX
    return (
        <div className="hello-world">
            <h1>{greeting}</h1>
            <p>This is a React component in WordPress!</p>
        </div>
    );
};

// Modern JavaScript feature: Optional chaining
const rootElement = document.getElementById('hello-world-root');
if (rootElement?.innerHTML) {
    render(<HelloWorld />, rootElement);
}

You also have to enqueue the script within your theme’s functions.php file, or within your main plugin file:

function enqueue_hello_world_script() {
    wp_enqueue_script(
        'hello-world-script',
        get_template_directory_uri() . '/build/index.js',
        ['wp-element'],
        filemtime(get_template_directory() . '/build/index.js'),
        true
    );
}

add_action('wp_enqueue_scripts', 'enqueue_hello_world_script');

Once you run the npx wp-scripts build command, wp-scripts will transpile your modern JavaScript and JSX to create a browser-compatible build/index.js file.

Code quality checks and sophisticated linting

The wp-scripts package includes several tools to help you maintain quality code and enforce a consistent style across your projects: Along with ESLint and Prettier, you can also access stylelint for CSS and SCSS linting.

The first step is to add the linting scripts to your package.json file:

"scripts": {
  "lint:js": "wp-scripts lint-js",
  "lint:css": "wp-scripts lint-style",
  "lint": "npm run lint:js && npm run lint:css"
}

Next, create custom configuration files in your project root directory. For example, ESLint requires you to work within the .eslintrc.js file. This example (in part) enforces using template literals for strings in your JavaScript code:

…
module.exports = {
  extends: [
    'plugin:@wordpress/eslint-plugin/recommended',
  ],
  rules: {
    // Custom rules here
    'no-console': 'error',
    'react-hooks/exhaustive-deps': 'warn',
    'prefer-template': 'error',
  },
};
…

For stylelint, you edit the .stylelintrc.js file:

…
module.exports = {
  extends: [
    '@wordpress/stylelint-config/scss',
  ],
  rules: {
    // Custom rules here
    'selector-class-pattern': '^[a-z]+(-[a-z]+)*$',
    'max-nesting-depth': 3,
  },
};
…

If you maintain a large codebase across multiple projects, having a consistent code style is crucial. This way, you can extend the default ESLint and stylelint configurations to enforce your agency’s coding standards.

From here, you can run npm run lint to set this process in motion, extended with the specific linter type. For example, if you have code that states some typical concatenation…

const name = "World";
console.log("Hello " + name + "!");

…running npm run lint:js will flag an error and suggest you use a template literal instead:

const name = "World";
console.log(`Hello ${name}!`);

This is an invaluable way to lint your WordPress theme or plugin code and gives you the scope to tailor the rulesets to your specific needs and standards.

Unit testing

Unit testing is crucial to ensure reliability and maintainability within your codebase. The tools wp-scripts uses as its testing framework is Jest.

When you run the test command, Jest looks for files with .test.js or .spec.js extensions, or for files in a __tests__ directory. It then runs the tests defined in these files and reports the results.

You first need to reference the test script within your package.json file:

…
"scripts": {
  "test": "wp-scripts test-unit-js"
}
…

If you need to, create a file such as src/utils.js:

…
export function capitalizeString(str) {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

export function sum(a, b) {
  return a + b;
}
…

From here, create a test file, such as src/__tests__/utils.test.js:

import { capitalizeString, sum } from '../utils';

describe('capitalizeString', () => {
  it('capitalizes the first letter of a string', () => {
    expect(capitalizeString('hello')).toBe('Hello');
  });
  it('returns an empty string if given an empty string', () => {
    expect(capitalizeString('')).toBe('');
  });
});

describe('sum', () => {
  it('adds two numbers correctly', () => {
    expect(sum(2, 3)).toBe(5);
  });
  it('handles negative numbers', () => {
    expect(sum(-1, 1)).toBe(0);
  });
});

Once you run the npm run test command, wp-scripts will automatically find and execute all files with the .test.js extension. You can also extend the default Jest configuration to support any advanced testing needs, such as test coverage:

// jest.config.js
const defaultConfig = require('@wordpress/scripts/config/jest-unit.config');
module.exports = {
  ...defaultConfig,
  setupFilesAfterEnv: ['<rootDir>/tests/setupTests.js'],
  collectCoverageFrom: [
    'src/**/*.js',
    '!src/tests/**/*.js',
    '!src/vendor/**/*.js',
  ],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 80,
      lines: 80,
      statements: 80,
    },
  },
};

This configuration adds a custom setup file, specifies files to include in coverage reports, and sets coverage thresholds to ensure comprehensive test coverage across your projects. When you run these tests, Jest will provide output that shows any passing and failing tests.

Expanding the capabilities of your unit testing in this way can offer a significant enhancement to the quality and reliability of your WordPress themes and plugins and streamline your whole development process.

How to integrate wp-scripts into your workflows

The scope of using wp-scripts is as wide as you need it to be. To illustrate this, let’s review some quick-fire approaches you could take in using wp-scripts to automate typical tasks.

Creating reusable project templates

You’ll likely need to start new projects frequently — maybe even every day. Creating a custom project template through preconfiguring wp-scripts preconfigured can save you a lot of setup time.

You can start with a base project: a new WordPress theme or plugin that includes your wp-scripts setup:

mkdir my-agency-base-theme
cd my-agency-base-theme
npm init -y
npm install --save-dev @wordpress/scripts

Next, set up the project structure, and create the necessary directories and files:

mkdir src build
touch src/index.js src/style.scss
touch functions.php style.css

At this point, you configure wp-scripts and update the package.json file with relevant commands:

{
  "scripts": {
    "build": "wp-scripts build",
    "start": "wp-scripts start",
    "lint:js": "wp-scripts lint-js",
    "lint:css": "wp-scripts lint-style",
    "test": "wp-scripts test-unit-js"
  }
}

You can expand upon this to create configurations for webpack, ESLint, and stylelint.

To make this a reusable template that is simple to access, a GitHub repo is ideal. For instance, consider a remote origin of https://github.com/your-agency/theme-template.git.

When you begin a new project, you can run a straightforward command:

npx create-wordpress-theme@latest my-new-theme --template your-agency/theme-template

This will clone your template repo and set up a new theme with your predefined wp-scripts configuration.

You can customize the template further by adding agency-specific boilerplate code, such as commonly used functions or components. It’s important to keep this template repository current, using the latest wp-scripts version and implementing any workflow improvements you decide upon.

Version control and collaboration

You can do more when it comes to wp-scripts and working with version control. Often though, you should implement some typical practices to ensure you keep code quality high:

  • Include package.json and package-lock.json in version control. This ensures all team members will use the same dependencies.
  • Make sure you include build artifacts such as /build and /node_modules within your .gitignore file.
  • Ensure you reference all of the scripts you need within your package.json file before you commit it.
  • Consider using a .nvmrc file to specify the correct Node.js version for your project.

You might choose to implement pre-commit hooks through tools such as Husky. This is a great way to run a linter before each commit, as just one example:

…
"husky": {
    "hooks": {
        "pre-commit": "npm run lint:js && npm run lint:css"
    }
}
…

This way, you can ensure you lint and run tests automatically before commits and pushes. It’s another way you can maintain code quality across your team.

Continuous Integration and Continuous Deployment (CI/CD)

Integrating wp-scripts into your CI/CD pipeline can streamline your deployment process for both themes and plugins. GitHub Actions is just one way to integrate this into your wp-scripts configuration.

The first step is to create a dedicated workflow file within a workflows directory of your repo:

name: CI/CD

on:
  push:
    branches: [ main ]
  pull_request:
    branches: [ main ]
jobs:
  build-and-test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - name: Use Node.js
      uses: actions/setup-node@v2
      with:
        node-version: '14'
    - name: Cache dependencies
      uses: actions/cache@v2
      with:
        path: ~/.npm
        key: ${{ runner.OS }}-node-${{ hashFiles('**/package-lock.json') }}
    - name: Install dependencies
      run: npm ci
    - name: Run linters
      run: |
        npm run lint:js
        npm run lint:css
    - name: Run tests
      run: npm run test
    - name: Build
      run: npm run build
    - name: Deploy
      if: github.ref == 'refs/heads/main'
      run: |
        # Add your deployment script here
        # For example, using rsync to a remote server:
        # rsync -avzc --delete ./build/ user@example.com:/path/to/wp-content/themes/your-theme/

The deployment step will vary based on your host. You might use rsync, integrate with services like DeployHQ or Buddy, or go for a simple cURL integration. If your deployment requires passwords or keys, you should add them as secrets to your GitHub repository settings.

This workflow runs linters, tests, and builds your project on every push and pull request. Best of all, it deploys only when you push changes to the main branch.

Creating a custom command line interface (CLI) tool

If you need custom tools, wp-scripts can assist. For instance, you might want to deploy a custom CLI tool that fits the needs of your agency.

In some cases, your tool will need some dependencies:

npm install @wordpress/scripts commander chalk

Here, Commander parses command line arguments, and chalk improves the visual display of the output text.

From here, you can begin to code the tool leveraging wp-scripts. Here’s an example of how that file would look:

#!/usr/bin/env node
const { program } = require('commander');
const { spawn } = require('child_process');
const path = require('path');
const chalk = require('chalk');

const wpScripts = path.resolve(__dirname, './node_modules/.bin/wp-scripts');

const runWpScripts = (script, args) => {
  console.log(chalk.blue(`Running wp-scripts ${script}...`));
  const result = spawn(wpScripts, [script, ...args], { stdio: 'inherit' });
  result.on('exit', (code) => {
    if (code !== 0) {
      console.log(chalk.red(`wp-scripts ${script} failed with code ${code}`));
    }
  });
};

program
  .version('1.0.0')
  .description('Custom WordPress development CLI for Agency XYZ');

program
  .command('build')
  .description('Build the project')
  .action(() => runWpScripts('build'));

program
  .command('start')
  .description('Start the development server')
  .action(() => runWpScripts('start'));

program
  .command('lint')
  .description('Lint JavaScript and CSS files')
  .action(() => {
    runWpScripts('lint-js');
    runWpScripts('lint-style');
  });

program
  .command('test')
  .description('Run unit tests')
  .action(() => runWpScripts('test-unit-js'));

program
  .command('deploy')
  .description('Deploy the project')
  .action(() => {
    console.log(chalk.green('Deploying project...'));
    // Add your deployment logic here
    // For example:
    // spawn('rsync', ['-avz', 'build/', 'user@server:/path/to/wordpress/wp-content/themes/your-theme/']);
  });

program.parse(process.argv);

Adding the bin field to your package.json file lets you make the CLI tool an executable:

…
{
  "name": "agency-wp-cli",
  "version": "1.0.0",
  "bin": {
    "agency-wp": "./cli.js"
  },
  // ... other fields
}
…

To link the CLI for a local installation, you can simply run npm link. Now, you can test the CLI out in your Terminal app:

agency-wp build
agency-wp lint
agency-wp deploy

You should publish the tool to a private npm registry so other team members can install it at their leisure:

npm publish --registry=https://your-private-registry.com

When you need it, you only need to run npm install --save-dev agency-wp-cli to install your tool. From here, you can reference the CLI within package.json:

{
  "scripts": {
    "build": "agency-wp build",
    "start": "agency-wp start",
    "lint": "agency-wp lint",
    "test": "agency-wp test",
    "deploy": "agency-wp deploy"
  }
}

Creating and using a tool like this ensures everyone in your agency uses the same commands and processes. This can reduce inconsistencies and streamline your WordPress development workflow even further.

Performance optimization

When managing multiple high-traffic WordPress sites, your performance optimization becomes crucial to your delivery. There are several advanced techniques wp-scripts can help you implement.

Advanced code splitting

For instance, code splitting lets you break your JavaScript bundle into smaller chunks, which you can load on demand. This can boost your initial loading times, especially for large applications.

First off, modify your webpack.config.js file to enable code splitting:

const defaultConfig = require('@wordpress/scripts/config/webpack.config');

module.exports = {
  ...defaultConfig,
  entry: {
    main: './src/index.js',
    admin: './src/admin.js',
  },
  output: {
    filename: '[name].js',
    chunkFilename: '[name].[contenthash].js',
  },
  optimization: {
    ...defaultConfig.optimization,
    splitChunks: {
      chunks: 'all',
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name(module) {
            const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
            return `vendor.${packageName.replace('@', '')}`;
          },
        },
      },
    },
  },
};

Throughout your JavaScript code, you use dynamic imports to split it into smaller chunks:

// Instead of: import { heavyFunction } from './heavyModule';

button.addEventListener('click', () => {
  import('./heavyModule').then(module => {
    module.heavyFunction();
  });
});

You also need to enqueue each split within your WordPress files:

function enqueue_split_scripts() {
  $asset_file = include(get_template_directory() . '/build/index.asset.php');  

  wp_enqueue_script('main', get_template_directory_uri() . '/build/main.js', $asset_file['dependencies'], $asset_file['version'], true);
  wp_enqueue_script('admin', get_template_directory_uri() . '/build/admin.js', $asset_file['dependencies'], $asset_file['version'], true);
}
add_action('wp_enqueue_scripts', 'enqueue_split_scripts');

This should give you lower loading times and doesn’t take too long to implement either.

Tree shaking

In the context of JavaScript, ‘tree shaking’ is how you get rid of unused code. Both wp-scripts and webpack perform tree shaking for production builds, but you can optimize it further. The application is more complex than we give here, but regardless, you want to ensure you use ES6 import and export syntax:

// Good for tree shaking
export function usedFunction() { /* ... */ }

// Bad for tree shaking
module.exports = {
  usedFunction: function() { /* ... */ },
};

Next, specify those files with ‘side effects’

{
  "name": "your-package",
  "sideEffects": ["*.css", "*.scss"]
}

…or mark it as free from side effects:

{
  "name": "your-package",
  "sideEffects": false
}

Some larger libraries don’t support tree shaking, as well as others. In these cases, you should use a specific plugin for the job:

npm install --save-dev babel-plugin-transform-imports

This will also mean you should update your babel configuration files too for the most optimal and error-free installation.

Asset optimization

The wp-scripts build process will minimize CSS and JavaScript files for you, and you can take this further too. For example, you can install a specific image optimization plugin:

npm install --save-dev imagemin-webpack-plugin

Once you add this to your webpack config file, you can use resource hints by adding the right code to your functions.php file or main plugin file:

function add_resource_hints( $urls, $relation_type ) {
  if ( 'preconnect' === $relation_type ) {
    $urls[] = 'https://fonts.googleapis.com';
    $urls[] = 'https://fonts.gstatic.com';
  }
  return $urls;
}

add_filter( 'wp_resource_hints', 'add_resource_hints', 10, 2 );

A task like this shows the flexibility you have with wp-scripts, in as much as how you can tailor it to your agency or project needs.

Analyze bundle size

Understanding your bundle composition is crucial for optimization. With wp-scripts, you can make it easy with the --analyze flag.

npm run build -- --analyze

The first step is to add the relevant script to your package.json file:

{
  "scripts": {
    "analyze": "wp-scripts build --analyze"
  }
}

Once you run the analyze command, it will generate a report that shows the size of each module in your bundle. This simple implementation helps you identify areas for optimization.

Implementing Critical CSS

Your site’s critical CSS is the bare minimum your page requires to load above-the-fold content. Putting this CSS inline can improve the perceived load time.

Achieving this requires the Critical CSS Webpack plugin:

npm install --save-dev critical-css-webpack-plugin

The next job is to update your webpack config file to reference the plugin:

const CriticalCssPlugin = require('critical-css-webpack-plugin');
const defaultConfig = require('@wordpress/scripts/config/webpack.config');

module.exports = {
  ...defaultConfig,
  plugins: [
    ...defaultConfig.plugins,
    new CriticalCssPlugin({
      base: 'dist/',
      src: 'index.html',
      target: 'styles/critical.css',
      extract: true,
      inline: true,
      minify: true,
      dimensions: [
        {
          height: 500,
          width: 300,
        },
        {
          height: 900,
          width: 1300,
        },
      ],
    }),
  ],
};

In order to use it, you need to add a snippet to your header.php file:

<style>
  <?php echo file_get_contents(get_template_directory() . '/build/styles/critical.css'); ?>
</style>

This essentially extracts and inlines critical CSS for a faster initial render. It generates critical CSS for specific viewport sizes, which can improve the perceived load time of your themes.

Summary

For agency development, wp-scripts can be a powerful tool that can significantly enhance your workflow for both theme and plugin projects. By providing a standardized build process, modern JavaScript support, and integrated testing and linting tools, wp-scripts lets you focus on creating high-quality WordPress projects while automating some of the most important tasks.

Leveraging wp-scripts doesn’t only help you keep up with modern development practices. It’s a way to position yourself at the forefront of WordPress development, ready to tackle the challenges and opportunities your agency has to face.

Does wp-scripts offer the functionality and scope you need for your agency development projects? Share your thoughts with us in the comments section below!

The post Advanced WordPress development: how to build your next project with wp-scripts appeared first on Kinsta®.

]]>
https://kinsta.com/blog/wp-scripts-development/feed/ 0