WordPress.com News

The latest news on WordPress.com and the WordPress community.

Open Enrollment at WordPress.com: Free Websites for Students  17 Sep 2024, 2:06 pm

Your online presence is paramount to the success and well-being of your future self. Whether it’s for sharing your latest creative project, building an impressive portfolio, or simply expressing your ideas, owning a personal website gives you the power to control your online identity. It’s a space where you can showcase your work, share your story, and set yourself apart in a sea of digital noise.

A simple website can, in fact, change the world. 

You are the future of the web 

At WordPress.com, we know that students are at the forefront of driving online culture. Michael Dell founded Dell while he was a student at the University of Texas. Google came to life when Larry and Sergey were at Stanford. Mark Zuckerberg was 19 when he started Facebook. We could keep going. 

To kickstart your own world-changing ideas, we want to give you a free website. 

Starting this week, university students can get a free Premium WordPress.com website for one year. We’re offering this opportunity to the first 1,000 students who sign up.

Investing in yourself—here’s what you get with a WordPress.com premium plan  

A website is more than a tool. It’s an investment in your future. As the job market becomes increasingly competitive, having an online space where you can display your work, write about your passions, and connect with like-minded people is invaluable. From resumes to portfolios to blogs, your WordPress.com site will grow as you do.

Here’s what’s included when you take advantage of this free website offer: 

  • Free custom domain name for the first year: Choose a personalized domain that reflects your identity.
  • Premium themes: Kickstart your site with professionally designed, fully customizable templates.
  • 13 GB of storage: Plenty of room to host your photos, videos, and other media, with ownership that’s entirely yours.
  • SSL certificate: Your site is secure and protected by industry-standard encryption.
  • Ad-free experience: Build and manage your site without ads distracting your visitors.

No matter what you’re creating, WordPress.com’s Premium plan gives you all the tools you need to succeed.

How to secure your free website 

Here’s how you can grab this amazing deal:

  1. Submit the interest form ASAP: Head over to our campaign landing page and fill out the form with your details. Be quick—only the first 1,000 students will get the free site!
  2. Verify your student status: After you’ve submitted the form, you’ll receive an email asking you to verify your student status through VerifyPass. This step ensures that our offer goes to real students.
  3. Claim your free website: Once your student status is verified, you’ll receive a unique coupon code that allows you to create a new Premium plan website for free.
  4. Build your site: Choose your domain, select a theme, and start building! 

This offer is perfect for students looking to stand out in their personal and professional journeys. Don’t miss out on this chance to create a space that’s truly your own.

Get started right away  

Having your own website is a game-changer in an online world increasingly controlled by social media algorithms. You’ll stand out by breaking the mold and announcing yourself as an individual, unmoved by the platform of the moment. 

WordPress.com is here to help you take that leap.

Take control of your digital identity. Sign up now and claim your free website while spots are still open!

Connect With More Clients: Our Partner Directory Has Arrived 16 Sep 2024, 5:35 pm

Since we launched the Automattic for Agencies program earlier this summer, we’ve helped agencies save thousands of dollars and countless developer hours.

Today, we’re making it easier than ever for agencies to connect with potential clients by presenting the new WordPress.com Partner Directory. This directory lists top-tier agencies for our customers who are looking for a partner for their web development projects.

If your agency’s growth is top of mind, there’s no better time to join Automattic for Agencies. In addition to saving time and money, your company could be eligible for a listing in our official partner directory, paving the way for more qualified leads and, ultimately, happy clients.

Get your agency in front of eager customers 

When someone needs a professional website, it can be hard to find the right agency to work with. Sifting through search engine results and going through credentials takes a lot of time and energy, which can leave them exhausted before they even get to your digital door. With the launch of the partner directory, we’re making it easier for consumers to find and connect with vetted, talented agencies—like yours.

When you apply to the agency directory, your application will be reviewed to assess critical areas like security, performance, and adherence to different business requirements. Accepted agencies can showcase their profile across the Woo, Jetpack, and Pressable brand directories via a single listing.

Visit our knowledge base for information about detailed application steps and criteria for inclusion as well as agency tiering and benefits.

Join Automattic for Agencies today

In addition to our curated directory, the Automattic for Agencies program brings together powerful hosting and a professional suite of plugins and tools in a flexible platform that allows your team to focus on building beautiful and functional websites.

At its core, Automattic for Agencies allows for the bulk purchasing and reselling of WordPress.com hosting plans (along with WooCommerce and Jetpack plugins). Our platform also equips you with direct referrals and invoicing, license management, and monitoring tools to assess security and performance needs across all your sites.

As an added bonus, Automattic for Agencies gives your agency access to volume discounts for your clients. Your first WordPress.com site starts at $30 per month; but with ten or more sites, the price drops to just $10 per site, per month. (All WordPress.com sites purchased through the agency program are on our powerful Business plan.)

Those savings coupled with our referral incentives make Automattic for Agencies a potent combination for growing your agency’s offerings and profitability.

Get started today and connect with new clients

Ultimately, our goal is to funnel more business your way, so that you can keep doing what you do best.

How to Connect Your WordPress Site to the Fediverse 13 Sep 2024, 4:32 pm

You created your website for a reason. Whether it’s showing off your art, passing on family recipes, or selling boutique high-performance yo-yos. (That may or may not be Doc Pop’s example.) You created your website to reach an audience and to communicate directly with that audience.

Wouldn’t it be great if there was an easier way for you to connect with them and make it easier for them to follow you and engage with your content online? In this final episode of the Fediverse Files, ‪Doc Pop walks you through how to connect your WordPress site to the Fediverse using ActivityPub.

Federate your website today and get 25% off a WordPress.com Business or Commerce hosting plan by using coupon code federate25—or click below:

WordPress.com and Developers: Roadmap Update 10 Sep 2024, 9:00 am

When I stepped in to run WordPress.com while Automattic CEO Matt Mullenweg was on sabbatical, my mission was to make WordPress.com the best and fastest host for WordPress developers and agencies. We cheekily called this initiative “Developers, Developers, Developers,” a reference to a certain point in tech history (wink wink, nudge nudge).

Since then, we’ve shipped a number of developer-focused features like GitHub deployments, a full hosting dashboard, and Studio, an open source local development environment. It’s been awesome to see the feedback rolling in:

WordPress.com has been crucial to my agency’s growth. Its intuitive UI allows me to quickly create sleek, functional websites for my clients, and their reliable hosting and support enable me to rest easy, knowing my sites are in good hands. —Brian Lalli, President @ moonrooster.com

WordPress.com really stands out with its exceptional performance and strong security. It’s a versatile platform that’s great for users at any skill level, and their support team is always incredibly helpful. For managed sites, we definitely think WordPress.com is the way to go. —Sonia Gaballa, Partner @ nudge.design

We aimed to provide clients with a reliable hosting service we could endorse without hesitation, ultimately resulting in satisfied clients. We found that service with WordPress.com. —Ajit Bohra, Founder @ lubus.in

As we round the corner into the final quarter of 2024, I’d like to offer a sneak peek into three themes guiding our work: performance, augmentation, and workflows. We hope you’re just as excited about them as we are, and we welcome you to join us in the journey by testing and providing feedback.

Answers for the age-old question: “Why is my site slow?”

an illustration of a computer screen with a yellow splash of color in the background and an arrow pointing upwards on the screen

WordPress sites should be fast, and it’s not always an easy thing.

When writing custom code, incorporating third-party libraries, or inheriting an existing site, it can be difficult to track down what’s causing poor performance and low scores. Is it a certain plugin, large photo sizes, slow code, or a combination of the three?

Our upcoming speed test tool innovates upon existing approaches to offer a set of performance recommendations tailored to your unique WordPress site. It will be totally free to use, and you’ll be able to sign up for regular updates. These notifications will come in handy as you change plugins, properly size photos, and optimize code because you’ll be alerted if anything changes unexpectedly.

In the not-so-distant future, the speed test tool will also be directly integrated into your WordPress.com dashboard. You’ll be able to see your performance across all of your sites, and better understand correlations between site changes and performance.

Interested in a free site performance consultation? Connect with me on LinkedIn or Twitter / X and I’d be happy to give you a demo!

Giving developers cybernetic powers

an illustration of a stick figure and a robot surrounding a computer screen and a lightbulb on top

Large Language Models (LLMs) are transforming all types of knowledge work. Was that sentence written by me or ChatGPT? You’ll never know!

At WordPress.com, we think of LLMs as a powerful way to augment developers’ work and give them superhuman-like powers. They’re great at doing things for people—writing blog post outlines, generating code, and creating images—but we think they’re also great for teaching and educating. 

As one practical example, Studio is getting an AI assistant. The Studio Assistant is trained on WordPress-specific documentation and has access to a bunch of context about your site. When you ask it for help, like “update all my plugins using WP-CLI,” it will put together an answer based on your site specs as well as provide an explanation for the answer. 

Download Studio for free today, connect your WordPress.com account (free or paid), and hit me up on on LinkedIn or Twitter / X to get a sneak peek!

Speeding up your daily grind

an illustration of a blue infinity sign in front of an orange splash of color with icons and the words 'smarter workflows' on top

When you’re developing on an open source platform like WordPress, there are hundreds (if not thousands) of different tools and workflows you can use to develop and ship websites. We’re focused on fostering quick and easy end-to-end workflows that help you deliver results that your clients love.

For example, you can now easily import sites into or export sites out of Studio. This is our first step towards a full, one-click WordPress.com syncing mechanism. Site cloning and a GitHub integration are also on our radar.

You also may have caught my tweet yesterday about our new Create Content Model prototype, which allows anyone to define custom post types and fields natively in the Block Editor.

Native content modeling for WordPress? 🤔

Not quite, but getting closer!

Check out Create Content Model, our latest @wordpressdotcom prototype, and let us know what you think! 🚀https://t.co/VJCp3VVIGc pic.twitter.com/Kp9alRqRmC

— Daniel Bachhuber (@dbchhbr) September 9, 2024

“GAME CHANGING!” and “Incredible!” were two of the dozens of positive reactions. We hope that our prototype spurs productive conversations within the core community.

We’re also making it easier for you to make money. For example, through our Automattic for Agencies program, freelancers and agencies can create a custom cart with a hosting plan and/or plugins, and then send the link to the client to check out. No need to worry about handling client credit card information or billing clients separately—it’s all done within a slick, easy-to-use interface.

a custom cart with a total and two products with two fields for Client email address and Custom message plus a blue 'Request payment from client' button

What do you want to see next?

This is just a quick preview of some of the big, impactful improvements you’ll be able to use soon as someone who hosts WordPress sites on WordPress.com. We’d love to know what other pain points you’d like to see us solve or features you’d like us to build! Either:


Original illustrations from David Neal (aka Reverent Geek). Come get a free avatar from him at the WordPress.com booth at WCUS next week!

Developer Q&A: John Kostak of Web Dev USA 5 Sep 2024, 12:07 pm

John Kostak has been building websites for longer than most social media networks have even been around. So splashy features don’t interest him much—he’s far more into performance, reliability, and compatibility. Which is why he and his company, Web Development USA, have been using WordPress.com from the start. 

In this fun Q&A, John shares more about his WordPress journey, what matters most to him as a developer, and a few of his favorite sites (in spite of the fact that it was like making him pick his favorite child). Note: The interview has been edited for clarity and length.

If John’s love for WordPress.com has you reconsidering your current hosting environment, you can learn more about our specs and get started at WordPress.com/hosting

Jeremy: How long have you been using WordPress and WordPress.com?

John: I have been building websites for about 15 or 16 years and started in a corporate environment for a large company. We never had an internal digital team and we basically created our own digital agency within this big corporate company. And that was pretty innovative back then. 

Then out of that, I spun off and started Web Development USA. That began in 2015, and so next year will be our 10th year, which is crazy to think about. But it went quickly because we really do enjoy this. And we look for people who find this to be a passion, as we do. 

Jeremy: Have you been using WordPress.com the entire time?

John: Yes we have. We started doing some testing with SiteGround and Elementor hosting, but we still like WordPress.com the best. You know you can go through a McDonald’s three miles away or 10,000 miles away on the other side of the planet and your lunch is going to be reasonably what you expect. That’s what WordPress.com feels like with its consistency and the familiarity of the UI and getting around. 

Jeremy: What do you like most about WordPress.com? Is it about ease of use on your side as a builder? Convenience for the customer? Both?

John: Resiliency. With Jetpack at the core and all the updates that it does, we just don’t have that much of a risk of things exploding, especially when we bring contractors in and out. We can always fall back to a previous state, and we have an exact record of it. We can get into PHP code. We can get into the very, very back end if we want. We can really be dangerous if we want, without being too afraid of it. 

Overall, it is certainly the all-around performance, security, and cadence that you use for backing up sites. 

Jeremy: What are some of your favorite features when building sites on WordPress? Do you have go-to themes, blocks, plugins, etc.?

John: Well, it’s changed over the years. We used to use standard old-school wireframe and theme templates that were very basic. And then we went into more “custom designer” mode, I would say, with templates and flashy designs. We graduated from Walmart t-shirts to Gucci t-shirts. And, you know, we enjoyed that for a while. 

Now we’re going back to robust wireframes and doing more from scratch. What’s more important now is really the entire stack, including performance and compatibility. You know, we just don’t have time to troubleshoot when we have some whizzy feature on the site. We don’t have time to go in and look for why the thing is down. So, we are sort of simplifying certain things and then standardizing on a certain stack.

Jeremy: What excites you about the future of WordPress.com? Are there any new features you’re especially excited to try out and use?

John: Honestly, we just don’t have time to get into a lot of that. We don’t look much to experimental features or anything like that. We’re trusting that by the time the feature or tool makes its way into being a standard of WordPress, it will be tried and true. We’re not looking for early adopter types of things anymore. 

The reality is that our value add is more about custom coding for integrations—maybe for a particular reservation system that has to shake hands and stay for a while on the site before it goes out to a third-party point of sale. It takes some custom coding there. That’s where our focus has really been—managed services and then a lot more programming. We’ve been onboarding more programmers in the last 18 months than we did the first eight years of the company.

Jeremy: Do you have a few favorite client sites that you can share?

John: Well, Jeremy, it’s like asking you who’s your favorite child. 

Jeremy: Depending on the week, I can give you a pretty good answer. 😊

John: Yeah, that’s a good point! Sure, I have a few:

TuckMusic.com

appalachian-air.com

kdmconsults.com

Get started at WordPress.com today 

Even though WordPress.com provides the freedom and tools to create stunningly beautiful and innovative websites, that’s not why developers choose us. Folks like John Kostak rely on WordPress.com because we have the most performant, secure, and compatible infrastructure out there. If you made it this far, you already know that you don’t have to take our word for it. 

Learn more about our top-notch hosting and get started: 

The Secrets of One of the World’s Largest Ad-Free Blogs 3 Sep 2024, 9:00 am

Since moving PostSecret to WordPress.com in 2013, Frank Warren’s iconic platform has empowered millions to share their secrets in a safe place. In the last ten years, that simple mission has propelled PostSecret to become one of the most highly trafficked ad-free blogs on the planet. In this video, Frank dives into the origins of his project and how Automattic’s tools help bring the mission to life.

Learn more about PostSecret and get an exclusive coupon when you click below:

Or, apply coupon code PostSecret15 at checkout for 15% off any plan.

Developer Q&A: Dika Fei of Jelly Pixel Studio 30 Aug 2024, 11:13 am

Dika Fei, like most founders, had a couple ideas that failed before hitting just the right note when he started his web development company, Jelly Pixel Studio. With a team of seven, Jelly Pixel Studio specializes in crafting unique and illustrative websites for a variety of clients worldwide. 

I had the chance to talk with Dika about why he loves WordPress.com, a few of his favorite tools, and examples of projects he’s most proud of. 

If Dika’s high praise convinces you to give WordPress.com another look, you can learn more about our specs and get started at WordPress.com/hosting

Jelly Pixel’s team. Dika is second from left, with the “peace” sign.

1. How long have you been working with WordPress and WordPress.com?

I’ve been working with WordPress for about 10 years now. When I first started, it was a bit like jumping into a lake and hoping there were no crocodiles! Back then, it wasn’t as obvious which CMS to choose. Joomla and Drupal were still pretty big, and it wasn’t clear that WordPress would be the best option. But we chose WordPress because it seemed more straightforward, and I’m so glad we made that decision. It was the right one. 

2. What do you like most about using WordPress.com for your clients?

If I knew nothing about it, I’d say WordPress.com works like magic! The uptime of websites on WordPress.com is often 100%, which really surprised me, especially compared to other hosting servers. It’s incredibly stable and scalable at a price point that’s hard to beat. 

Jelly Pixel is also part of Automattic for Agencies, and it’s impressive how the system scales, like running 10 CPUs that can go up to 100 when needed.

It’s a true “set it and forget it” experience in the WordPress industry. Let me know where you get your magic pixie dust from! 

3. What are your favorite tools or themes to use in your projects?

I love using GeneratePress and Advanced Custom Fields (ACF). 

GeneratePress is a lightweight theme that supports different approaches to web development, including full site editing. It’s a great starter theme for developers. 

Advanced Custom Fields is a well-known plugin, and I particularly appreciate how it now allows you to create Gutenberg blocks easily, handling the backend UI for you.

4. What recent WordPress features or updates are you excited about?

I’m really excited about the Interactivity API enabling more dynamic and interactive site features, akin to what we see with React. It’s still in its early days, but I think we’ll see more adoption soon.

5. What’s most important to you when building a WordPress site?

Stability and security are my top priorities. One of the biggest factors there is having a secure hosting environment. Many security issues come from improperly configured hosting, but with WordPress.com, you don’t have to worry about that. The secure server setup handles every vulnerability for you, which is a huge relief.

6. Can you share a few of your favorite client sites? Why do they stand out to you?

  • Screenshot

Ambient Lounge Japan, for its amazing product customization feature.

Workprint LA, for its overall design.

CNIB Access Labs, as a fully accessible and beautifully designed site. 

Get started at WordPress.com today

Beyond our customization options and extensability, what keeps Dika Fei and Jelly Pixel Studio using WordPress.com are our rock-solid security and performance specs. Those foundational aspects of developing and hosting sites can get overlooked amidst glitzy marketing campaigns. If you’re as impressed with our uptime as Dika, get started building today: 

Hot Off the Press: New WordPress.com Themes for August 2024 27 Aug 2024, 4:24 pm

The WordPress.com team is always working on new design ideas to bring your website to life. Check out the latest themes in our library, including great options for dog lovers, engaged couples, and interior design aficionados.


Bark

Bark is a pawsitively perfect theme for pet care pros, striking the perfect balance between professional and playful. With sections tailored to showcase your services, testimonials, and even a map of your service areas, Bark helps make your business the leader of the pack. The typography adds a touch of modern charm, while the warm color palette and rounded corners brings comfort to every page. And with four color schemes available, Bark has all the tricks to make your site fetch some serious attention.

Click here to view a demo of this theme.


Vows

Vows is the perfect theme for engaged couples who want to tie everything together in style. Inspired by the timeless elegance of wedding stationery and photography, Vows acts as a sleek, all-in-one link hub, making it easy to coordinate your big day. From centralizing information to sharing event details and visual themes, this theme does it all with grace. With sophisticated font pairings and style variations, Vows sets the perfect tone for your celebration.

Click here to view a demo of this theme.


Cottage

Cottage is the perfect theme for anyone who wants to share the warmth and charm of their home or interior design sensibilities with the world. Inspired by the cottagecore aesthetic, this theme wraps your content in an earthy, cozy color palette that feels like a warm cup of tea on a rainy day. With a stunning gallery page to showcase your space and a delightful background pattern that adds a touch of whimsy, this will be your go-to design for all things homey and beautiful. Whether you’re blogging about decor or sharing your latest design inspiration, Cottage makes your site feel like home.

Click here to view a demo of this theme.


Hola

Hola was built for bloggers and newsletter creators who want their words to shine. A sleek variation of the Hey theme, Hola keeps it simple with a text-forward design that highlights your latest posts in a clean, straightforward layout. The striking header is created by adding a black-and-white image to a Cover Block with a preset duotone—an effect also applied to featured images, avatars, and the site logo.

The theme’s expanded color palette and four unique style variations bring a bit of personality to the mix, whether you’re vibing with cool blues, the vibrant magenta, or earthy tones. No matter your aesthetic, Hola offers a minimalist canvas with just the right pop of flair.

Click here to view a demo of this theme.


To install any of the above themes, click the name of the theme you like, which brings you right to the installation page. Then click the “Activate this design” button. You can also click “Open live demo,” which brings up a clickable, scrollable version of the theme for you to preview.

Premium themes are available to use at no extra charge for customers on the Personal plan or above. Partner themes are third-party products that can be purchased for $99/year each on the Business plan and above.

You can explore all of our themes by navigating to the “Themes” page, which is found under “Appearance” in the left-side menu of your WordPress.com dashboard. Or you can click below:

The Fediverse Files: The Magic of Federation 23 Aug 2024, 2:52 pm

Remember when commenting on blogs and interacting with other commenters was one of the core pieces of enjoying the web? Matthias Pfefferle is making commenting cool again with ActivityPub for WordPress, a plugin that seamlessly connects your WordPress website to the fediverse. 

In this interview, Doc Pop and Matthias talk about fediverse applications that apply beyond social media—and where the ActivityPub protocol can go in the future. 

Will you be one of those people? Federate your website today and get 25% off a WordPress.com Business or Commerce hosting plan by using coupon code federate25—or click below:

Building Studio in Public: Maintaining High Performance in Our Local Development App for Enhanced UX 20 Aug 2024, 9:00 am

We’re back with Part 2 of our “Building Studio in Public” series! Today, we’re diving into the challenges we faced while optimizing Studio’s performance. This post will be especially valuable if you’re developing an Electron app and dealing with performance issues or if you’re simply curious about how the Studio app functions behind the scenes.

If you’re following the series, be sure to check out our first post: Using WordPress Components and Tailwind CSS in our Local Development App.

As a reminder, Studio is our free, open source local development app. It’s based on Electron (the focus of today’s post!) and is currently available for Mac and Windows.

Overcoming the challenges of running local development sites

Running a local development site can be complex, often requiring the setup of multiple tools. A typical approach involves using multi-container applications like Docker and Docker Compose in addition to setting up a web server with a WordPress installation and a MySQL database. This process can become even more challenging when managing multiple sites simultaneously.

Studio was designed to simplify this process, allowing users to set up sites quickly without any prior configuration. This capability is powered primarily by the WordPress Playground project, which enables anyone to run a fully functional WordPress site within a browser or Node.js environment. 

For each site created with Studio, we run a basic web server using ExpressJS to handle web requests and use WordPress Playground to process them.

Initially, this was implemented in the Electron-based Studio app without noticeable performance issues.

However, as we expanded our testing across Mac and Windows, we observed some slowness in UI interactions when managing and navigating sites. Everything seemed properly configured, but something was clearly off.

A gif of someone squinting their eyes

Keeping the main process lightweight

As we delved into these performance issues, we discovered that running sites within Electron’s main process was the primary cause of the slowdown. Processing web requests and executing the associated PHP code for WordPress in the main process added extra load, which negatively impacted other operations, aka that UI slowness we were seeing.

screenshots showing the differences of starting a site and creating a site in Electron's main process vs the dedicated process

Electron’s documentation is incredibly valuable for addressing performance issues, particularly those related to blocking the main process. It was clear that maintaining a lightweight main process is crucial, and avoiding heavy or blocking operations in this context is essential. However, this realization presented a new challenge: how do we detach the running sites from the main process?

Spawning dedicated processes

To tackle the performance issues, we adopted the tried-and-true strategy of “divide and conquer.” 

The idea was to run Studio’s sites in dedicated processes, separate from the main one. Since Electron is built on Node.js, spawning child processes seemed like a plausible solution. However, Electron also offers a utilityProcess utility, which behaves similarly to Node’s child processes, but operating at the browser level and aligning more closely with Electron’s app model.

While this approach promised to alleviate the load on the main process, it also introduced additional complexity. We had to manage these new processes and handle communication between the main and dedicated processes via messages. Additionally, we encountered challenges related to the build configuration and using Webpack for building the application.

Below is a full example of implementing this approach (click to expand each example to see the full code):

Dedicated Process Manager (process.js):
const { app, utilityProcess } = require( 'electron' );

// This path should be calculated dynamically as the file could be in
// different locations depending on the build configuration
const PROCESS_MODULE_PATH = './process-child.js';

const DEFAULT_RESPONSE_TIMEOUT = 120000;

class Process {
	lastMessageId = 0;
	process;
	ongoingMessages = {};

	async init() {
		return new Promise( ( resolve, reject ) => {
			const spawnListener = async () => {
				// Removing exit listener as we only need it upon starting
				this.process?.off( 'exit', exitListener );
				resolve();
			};
			const exitListener = ( code ) => {
				if ( code !== 0 ) {
					reject( new Error( `process exited with code ${ code } upon starting` ) );
				}
			};

			this.process = utilityProcess
				.fork( PROCESS_MODULE_PATH, [], {
					serviceName: 'dedicated-process',
					env: {
						...process.env,
						IN_CHILD_PROCESS: 'true',
						APP_NAME: app.name,
						// Note that Electron context won't be available in the dedicated process.
						// Add here other environment variables that might be needed.
					},
				} )
				.on( 'spawn', spawnListener )
				.on( 'exit', exitListener );
		} );
	}

	// This is an example function. Feel free to add more for other purposes.
	async exampleFunc( command, args ) {
		const message = 'exampleFunc';
		const messageId = this.sendMessage( message, { command, args } );
		return await this.waitForResponse( message, messageId );
	}

	// It's important to keep in mind that the process will be running
	// until it's explicitly stopped.
	async stop() {
		await this.killProcess();
	}

	sendMessage( message, data ) {
		const process = this.process;
		if ( ! process ) {
			throw Error( 'The process is not running' );
		}

		const messageId = this.lastMessageId++;
		process.postMessage( { message, messageId, data } );
		return messageId;
	}

	async waitForResponse( originalMessage, originalMessageId, timeout = DEFAULT_RESPONSE_TIMEOUT ) {
		const process = this.process;
		if ( ! process ) {
			throw Error( 'The process is not running' );
		}
		if ( this.ongoingMessages[ originalMessageId ] ) {
			throw Error(
				`The 'waitForResponse' function was already called for message ID ${ originalMessageId } from the message '${ originalMessage }'. 'waitForResponse' may only be called once per message ID.`
			);
		}

		return new Promise( ( resolve, reject ) => {
			const handler = ( { message, messageId, data, error } ) => {
				if ( message !== originalMessage || messageId !== originalMessageId ) {
					return;
				}
				process.removeListener( 'message', handler );
				clearTimeout( timeoutId );
				delete this.ongoingMessages[ originalMessageId ];
				if ( typeof error !== 'undefined' ) {
					console.error( error );
					reject( new Error( error ) );
					return;
				}
				resolve( data );
			};

			const timeoutHandler = () => {
				reject( new Error( `Request for message ${ originalMessage } timed out` ) );
				process.removeListener( 'message', handler );
			};
			const timeoutId = setTimeout( timeoutHandler, timeout );
			const cancelHandler = () => {
				clearTimeout( timeoutId );
				reject( {
					error: new Error( `Request for message ${ originalMessage } was canceled` ),
					canceled: true,
				} );
				process.removeListener( 'message', handler );
			};
			this.ongoingMessages[ originalMessageId ] = { cancelHandler };

			process.addListener( 'message', handler );
		} );
	}

	async killProcess() {
		const process = this.process;
		if ( ! process ) {
			throw Error( 'The process is not running' );
		}

		this.cancelOngoingMessages();

		return new Promise( ( resolve, reject ) => {
			process.once( 'exit', ( code ) => {
				if ( code !== 0 ) {
					reject( new Error( `Process exited with code ${ code } upon stopping` ) );
					return;
				}
				resolve();
			} );
			process.kill();
		} ).catch( ( error ) => {
			console.error( error );
		} );
	}

	cancelOngoingMessages() {
		Object.values( this.ongoingMessages ).forEach( ( { cancelHandler } ) => {
			cancelHandler();
		} );
	}
}

module.exports = Process;

Dedicated Process Logic (process-child.js):
// Replace with initial setup logic based on the environment variables if needed.
console.log( `Run initial setup for app: ${ process.env.APP_NAME }` );

const handlers = {
	exampleFunc: createHandler( exampleFunc ),
};

async function exampleFunc( data ) {
	const { command, args } = data;
	// Replace this with the desired logic.
	console.log( `Run heavy operation ${ command } with args: ${ args }` );
}

function createHandler( handler ) {
	return async ( message, messageId, data ) => {
		try {
			const response = await handler( data );
			process.parentPort.postMessage( {
				message,
				messageId,
				data: response,
			} );
		} catch ( error ) {
			process.parentPort.postMessage( {
				message,
				messageId,
				error: error?.message || 'Unknown Error',
			} );
		}
	};
}

process.parentPort.on( 'message', async ( { data: messagePayload } ) => {
	const { message, messageId, data } = messagePayload;
	const handler = handlers[ message ];
	if ( ! handler ) {
		process.parentPort.postMessage( {
			message,
			messageId,
			error: Error( `No handler defined for message '${ message }'` ),
		} );
		return;
	}
	await handler( message, messageId, data );
} );
Run example (main.js):
async function runExample() {
	const process = new Process();
	await process.init();
	await process.exampleFunc( 'my-command', [ 'example', 100 ] );
}

…
app.whenReady().then( () => {
	runExample();
} );
…

Note: The code above has been adapted for use in a generic example Electron project. You can test it using Electron Fiddle.

Build configuration and Webpack

Our project build setup relies on Forge and Webpack. Implementing dedicated processes introduced extra complexity, as we initially bundled all the code into a single file. 

However, since dedicated processes require their code to run in isolation from the main process, we needed to separate the bundles. After adjusting the Webpack configuration, we successfully set it up to produce the necessary files.

Below is an example of the changes we applied (click to expand each example to see the full code):

Before:
import { type Configuration } from 'webpack';

export const mainConfig: Configuration = {
	// This is the main entry point for your application, it's the first file
	// that runs in the main process.
	entry: './src/index.ts',

...
After:
import path from 'path';
import { type Configuration, DefinePlugin } from 'webpack';

// Extra entries are bundled separately from the main bundle. They are primarily used
// for worker threads and forked processes, which need to be loaded independently.
const extraEntries = [
	{
		name: 'siteServerProcess',
		path: './src/lib/site-server-process-child.ts',
		exportName: 'SITE_SERVER_PROCESS_MODULE_PATH',
	},
	// Here you can configure other dedicated processes
];

export default function mainConfig( _env: unknown, args: Record< string, unknown > ) {
	const isProduction = args.mode === 'production';

	// Generates the necessary plugins to expose the module path of extra entries.
	const definePlugins = extraEntries.map( ( entry ) => {
		// The path calculation is based on how the Forge's webpack plugin generates the path for Electron files.
		// Reference: https://github.com/electron/forge/blob/b298b2967bdc79bdc4e09681ea1ccc46a371635a/packages/plugin/webpack/src/WebpackConfig.ts#L113-L140
		const modulePath = isProduction
			? `require('path').resolve(__dirname, '..', 'main', '${ entry.name }.js')`
			: JSON.stringify( path.resolve( __dirname, `.webpack/main/${ entry.name }.js` ) );
		return new DefinePlugin( {
			[ entry.exportName ]: modulePath,
		} );
	} );

	return {
		...mainBaseConfig,
		plugins: [ ...( mainBaseConfig.plugins || [] ), ...definePlugins ],
	};
}

export const mainBaseConfig: Configuration = {
	entry: {
		// This is the main entry point for your application, it's the first file
		// that runs in the main process.
		index: './src/index.ts',
		// Inject extra entries into the Webpack configuration.
		// These entries are primarily used for worker threads and forked processes.
		...extraEntries.reduce( ( accum, entry ) => {
			return { ...accum, [ entry.name ]: entry.path };
		}, {} ),
	},

...

Note: The code above is directly from Studio, written in TypeScript.

Bonus tip: avoid blocking file system operations

We also noticed performance issues when using synchronous file system operations when building Studio, specifically when using the synchronous versions of functions, which can block the main process. To prevent this, it’s best to use the promise-based or callback versions of these functions.

For example, instead of using:

fs.readFileSync( path, 'utf8' );

Use:

await fs.readFile( path, 'utf8' );

Ready to build?

If this information has piqued your interest, or if you’re developing WordPress sites, start leveraging the power of Studio today. It’s free, it’s open source, and it seamlessly integrates into your development workflow.

After downloading Studio, connect it to your WordPress.com account (free or paid) to unlock features like Demo Sites.

Want to contribute to Studio? Here are some GitHub issues you can dive into:

Page processed in 0.989 seconds.

Powered by SimplePie 1.3.1, Build 20121030175403. Run the SimplePie Compatibility Test. SimplePie is © 2004–2024, Ryan Parman and Geoffrey Sneddon, and licensed under the BSD License.