Builders https://wpengine.com/builders/ Reimagining the way we build with WordPress. Mon, 12 Aug 2024 13:19:14 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://wpengine.com/builders/wp-content/uploads/2024/05/wp-engine-favicon-32.png Builders https://wpengine.com/builders/ 32 32 On-Demand ISR Support for Next.js/Faust.js on WP engine’s headless WordPress Platform https://wpengine.com/builders/on-demand-isr-support-for-next-js-faust-js-on-wp-engines-headless-wordpress-platform/ https://wpengine.com/builders/on-demand-isr-support-for-next-js-faust-js-on-wp-engines-headless-wordpress-platform/#respond Mon, 12 Aug 2024 13:19:12 +0000 https://wpengine.com/builders/?p=31676 WP engine’s headless WordPress hosting platform is the go-to end-to-end solution for the headless approach. In this article, I will discuss and guide you through the easy implementation of the […]

The post On-Demand ISR Support for Next.js/Faust.js on WP engine’s headless WordPress Platform appeared first on Builders.

]]>
WP engine’s headless WordPress hosting platform is the go-to end-to-end solution for the headless approach. In this article, I will discuss and guide you through the easy implementation of the latest feature on the platform: Support for On-Demand ISR on Next.js/Faust.js. By the end of this article, you will have a better understanding of On-Demand ISR and using the headless WP platform to support it with Next.js/Faust.js.

Prerequisites

Before reading this article, you should have the following prerequisites checked off:

  • Basic knowledge of Next.js and Faust.js.
  • A WP engine headless WordPress account and environment set up.
  • Node.js and npm are installed on your local machine.

If you do not and need a basic understanding of Next.js and Faust.js, please visit the docs:

https://nextjs.org/docs

https://faustjs.org/tutorial/get-started-with-faust

What is On-Demand ISR?

On-Demand Incremental Static Regeneration (ISR) is a feature that allows you to manually purge the Next.js cache for specific pages, enabling more dynamic and timely updates to your site. Typically, in regular ISR when you set a revalidate time, such as 60 seconds, all visitors will see the same generated version of your site for that duration. The cache is only invalidated when someone visits the page after the revalidation period has passed.

With the introduction of On-Demand ISR in Next.js version 12.2.0, you can now trigger cache invalidation manually, providing greater flexibility in updating your site. This is particularly useful when:

  • Content from your headless CMS is created or updated.
  • E-commerce metadata changes, such as price, description, category, or reviews, are made.

This feature streamlines the process of reflecting changes on your site in real-time, ensuring that your content is always fresh and up-to-date.

Why Use it in headless WordPress?

In headless WordPress, the front end is decoupled from the WordPress backend, often using Next.js and Faust.js to render the website. This architecture offers several advantages, such as potential for improved performance, enhanced security, and greater flexibility in choosing front-end technologies.

However, one challenge with headless WordPress is ensuring that content changes in WordPress are reflected on the front end without sacrificing performance. This is where On-Demand ISR becomes crucial. By leveraging On-Demand ISR, you can achieve the following benefits:

Up-to-date Content: On-Demand ISR allows your site to fetch the latest content updates from WordPress manually, as needed. Unlike regular ISR, which checks for updates at specified intervals, On-Demand ISR lets you trigger cache invalidation whenever content is created or updated in WordPress. This ensures that users see the most recent content without waiting for a revalidation period.

Enhanced Performance: Since On-Demand ISR updates only the specific pages that need regeneration at the moment they are triggered, your site remains fast and responsive. Initial load times are minimized, and only the changed content is updated, reducing server load and build times.

SEO Benefits: Static pages are highly favored by search engines due to their speed and reliability. With On-Demand ISR, you maintain the SEO advantages of static generation while ensuring that your content is always fresh and relevant, as updates are reflected immediately after they are triggered.

Scalability: On-Demand ISR enables your site to handle large volumes of content efficiently. Whether you’re running a blog with frequent updates or an e-commerce site with dynamic product listings, On-Demand ISR ensures that your site scales seamlessly.

All those benefits got me stoked! Let’s get it on our Next.js and Faust.js sites!

Configuring Next.js with the headless WP Platform for On-Demand ISR

Let’s configure our Next.js application to work with On-Demand ISR.

Here is the docs link to the headless WordPress platform support for On-Demand ISR.

Atlas-Next Package

In your Next.js project, go to your terminal and install the @wpengine/atlas-next package:

npm install --save @wpengine/atlas-next

This package provides improved support on the headless WP platform. Once you install it, ensure it is in your project by navigating to your package.json file at the root of your project:

{
  "name": "atlas-on-demand-isr",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "@wpengine/atlas-next": "^1.3.0-beta.0",
    "next": "14.2.4",
    "react": "^18",
    "react-dom": "^18"
  },
  "devDependencies": {
    "eslint": "^8",
    "eslint-config-next": "14.2.4",
    "postcss": "^8",
    "tailwindcss": "^3.4.1"
  }
}

Now that you have verified the proper installation, staying at the root of your project,  modify your next.config.js file like so:

const { withAtlasConfig } = require("@wpengine/atlas-next");

/** @type {import('next').NextConfig} */

const nextConfig = {

 // Your existing Next.js config

};

module.exports = withAtlasConfig(nextConfig);

Faust.js Wrapper

If you are using Faust.js, all you need to do is modify your next.config.js file using the withFaust wrapper:

const { withFaust } = require("@faustwp/core")
const { withAtlasConfig } = require("@wpengine/atlas-next")

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Your existing Next.js config
}

module.exports = withFaust(withAtlasConfig(nextConfig))

Next, we need to verify that it works.  Run your app in dev mode via npm run dev and you should see this output in your terminal:

Stoked! It works!

Create an API route

The first thing we need to do is create an API route.  This will allow you to pass the path to be revalidated as a parameter.

Step 1. Create the API route file: Navigate to the pages/api directory in your Next.js project and create a new file named revalidate.js.

Step 2. Add the API Route code: Open revalidate.js and add the following code:

export default async function handler(req, res) {
  // Check for a secret token to authenticate the request
  if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
    return res.status(401).json({ message: 'Invalid token' });
  }

  const path = req.query.path;

  // Ensure the path parameter is provided
  if (!path) {
    return res.status(400).json({ message: 'Path query parameter is required' });
  }

  try {
    // Revalidate the specified path
    await res.revalidate(path);
    return res.json({ revalidated: true });
  } catch (err) {
    return res.status(500).json({ message: 'Error revalidating', error: err.message });
  }

Step 3.  Configure the environment variables: Create a .env.local file in the root of your project if it does not exist already.

Step 4. Next, create a secret token. This code sets up an API route that checks for a secret token for security, validates the presence of the path parameter, and triggers the revalidation of the specified path.

Once you have Node.js installed, you can use it to generate a secret token.

Open Your Terminal: Start by opening your terminal or command prompt.

Generate a Secret Token: Run the following command in your terminal:

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))

This command uses the crypto module to generate a 32-byte random string in hexadecimal format. The output will be your secret token.

Once the token is generated, copy and paste it into your .env.local file and give it an environment variable name e.g. `REVALIDATION_SECRET` 

It should look like this: REVALIDATION_SECRET=your-secret-key

Use the API route to configure cache revalidation

To configure cache revalidation in the headless WordPress setup, you could follow one of the approaches below:

Use a webhook plugin: You can use plugins like WP Webhooks to enable webhook functionality and trigger the API endpoint you’ve just created when relevant events occur, such as when a post is published or updated.

When you have your secret key generated and need an API endpoint, append a query string parameter to it with the key and value pair, where the key is secret and the value is the secret token. For instance:

http://localhost:3000/api/revalidate?secret=your-secret-key

This is the endpoint you can embed in a field that requires it when using a plugin like WP Webhooks. The field will correlate to whatever action will happen when the endpoint is hit such as updating a post.  

Set up WordPress hooks: You can also add actions in your WordPress theme or plugin to send requests to your Next.js API route. Here’s an example using the wp_remote_post function in php, which will send a POST request to the Next.js API route whenever a post is saved in WordPress, triggering the revalidation of the corresponding path:

function trigger_revalidation($post_id) {
  $url = 'https://your-nextjs-site.com/api/revalidate?secret=your-secret-token&path=' . get_permalink($post_id);
  
  $response = wp_remote_post($url);

  if (is_wp_error($response)) {
    error_log('Error triggering revalidation: ' . $response->get_error_message());
  }
}
add_action('save_post', 'trigger_revalidation');

Headless WordPress Platform User Portal

We now have On-Demand ISR set up with the proper configuration. The last steps are to connect our remote repository to WP engine’s headless WP platform, git push any changes, and observe On-Demand ISR working in all its cache invalidation glory.

If you have not connected your local project to a remote repository, go ahead and do so.  WP engine headless platform supports GitHub, Bitbucket, and GitLab.

Once you have connected your remote repository and added all your necessary environment variables, go ahead and build the app. If you have done this with an existing repo, you can git push the change, which will trigger a build.

When the application is finished in the build step, you are on the main page of the WP engine headless WP portal.  Navigate over to the Logs subpage:

In the Logs subpage, click the “Show logs” button on the Runtime option:

You should see the same output focusing on line 6 as you did in your terminal to ensure it’s working properly:

Awesome!!! It is implemented and working in runtime.  Now, when you edit or input new content in your WP backend, and then visit the live URL of the WP engine headless WP site you just deployed, the ISR should work on demand like so:

Limitations

At the moment, the headless WP platform supports On-Demand ISR with the following limitations:

  1. Requires @wpengine/atlas-next package: To enable On-Demand ISR on Atlas, you must use the @wpenngine/atlas-next package and follow the setup steps outlined in the previous sections of this document.
  2. On-demand ISR for App Router is not supported: The App Router is a new routing system in Next.js that enhances routing capabilities with features like server components and nested layouts. However, Atlas currently supports On-Demand ISR only in the context of the traditional Pages Router. This means that methods like revalidatePath and revalidateTag, which are used for revalidation in the App Router, are not compatible with the headless WP platform’s ISR mechanism. For more details on the App Router and its data fetching methods, you can refer to the Next.js documentation here.
  3. Rewrites are not supported: Rewrites in Next.js allow you to change the destination URL of a request without altering the URL visible to the user. However, On-Demand ISR on the headless WP platform does not support rewrites. This means that if your Next.js application relies on rewrites, the On-Demand ISR feature might not function as expected. You can learn more about rewrites here.
  4. Not compatible with Next.js I18N: Since Next.js uses rewrites for internationalization, this feature is not supported on the headless WP platform due to the rewrite limitation mentioned above.
  5. Next.js >=13.5 is required: To be able to use this feature, you need to update your application to Next.js version 13.5 or higher.

NoteRedirects (which, unlike rewrites, actually change the URL in the user’s browser to the specified destination) are supported.

If you want to give us feedback on how we can make things better for this feature or anything else with the platform, please visit our feedback form.

Conclusion

Implementing On-Demand Incremental Static Regeneration (ISR) with Next.js and Faust.js on WP engine’s headless WP platform is a game-changer for maintaining performance and up-to-date content in a headless WordPress setup. By following the steps outlined in this guide, you can leverage On-Demand ISR to ensure your site remains both fast and current, without the need for full rebuilds. 

The integration with the platform also simplifies the deployment and management process, providing a seamless workflow from development to production. 

As always, we look forward to hearing your feedback, thoughts, and projects so hit us up in our headless Discord!

The post On-Demand ISR Support for Next.js/Faust.js on WP engine’s headless WordPress Platform appeared first on Builders.

]]>
https://wpengine.com/builders/on-demand-isr-support-for-next-js-faust-js-on-wp-engines-headless-wordpress-platform/feed/ 0
Contributing to Open Source Projects https://wpengine.com/builders/contributing-to-open-source-projects/ https://wpengine.com/builders/contributing-to-open-source-projects/#respond Wed, 24 Jul 2024 21:55:02 +0000 https://wpengine.com/builders/?p=31667 This article aims to guide developers on best practices for contributing to Faust.js and other Open Source Software (OSS) and provide actionable steps for getting started with contributions. Whether you’re […]

The post Contributing to Open Source Projects appeared first on Builders.

]]>
This article aims to guide developers on best practices for contributing to Faust.js and other Open Source Software (OSS) and provide actionable steps for getting started with contributions. Whether you’re a seasoned developer or just starting, this guide will help you navigate the OSS ecosystem and make meaningful contributions.

What Defines an OSS?

Open Source Software (OSS) is software released with a license that allows anyone to view, modify, and distribute the source code. This openness fosters a collaborative environment where developers can contribute, innovate, and improve the software. OSS is the backbone of many critical technologies and has a profound impact on the software industry by promoting transparency, security, and community-driven development.

Understanding the Open Source Ecosystem

In order to understand the OSS ecosystem, let’s define the types of contributions to it.  There are four main types of contributions:

  1. Code Contributions: Adding new features, fixing bugs, and improving software performance and security are common ways to contribute code. These contributions directly impact the project’s functionality and reliability.
  2. Documentation Improvements: Clear and comprehensive documentation is crucial for any OSS project. Contributing to user guides, API references, and tutorials helps new users and contributors understand and utilize the software effectively.
  3. Community Support: Helping other users in forums, social media, and chat channels builds a supportive and inclusive community. Providing answers, sharing knowledge, and offering guidance are valuable contributions.
  4. Testing and Bug Reporting: Identifying and reporting bugs, performing quality assurance, and testing new features ensure the software remains robust and reliable. Thorough testing and detailed bug reports help maintainers address issues efficiently.

Now that we have listed out the types of contributions, let’s discuss the licensing and legal considerations in OSS.

In OSS, the three most common types of licenses are listed below:

  • MIT License: Permissive and simple, allowing almost unrestricted reuse. It’s one of the most popular OSS licenses due to its simplicity and flexibility.
  • GPL (GNU General Public License): This license requires derivative works to be open source. It ensures that software remains free and open for future generations.
  • Apache License: This license is similar to MIT but includes an explicit grant of patent rights from contributors. It is preferred for projects that want to protect against potential patent litigation.

Understanding Contributor License Agreements (CLAs):

CLAs are legal agreements that contributors must sign, giving the project permission to use their contributions. They clarify the rights and obligations of both contributors and project maintainers, ensuring that contributions can be used freely within the project.  The Faust.js project uses such an agreement.

Headless WordPress OSS

The three main OSS projects for headless WordPress that we use at WP Engine are Faust.js, WordPress, and WPGraphQL:

Faust.js: A toolkit for Next.js for building modern, headless WordPress sites. It simplifies the development of WordPress sites by leveraging the power of React and WPGraphQL.

WPGraphQL: WPGraphQL is a free, open-source WordPress plugin that provides an extendable GraphQL schema and API for any WordPress site.

WordPress: A content management system (CMS) powering a significant portion of the web. Its strong community and extensive ecosystem of plugins and themes make it a versatile and widely-used platform.

Contributions can include adding new features, fixing bugs, or enhancing the documentation. For example, you might implement a new WPGraphQL query, optimize performance, or write a tutorial.

Within the contribution areas, the focus might include improving core functionality, creating example projects, or enhancing developer tools. The Faust.js community is welcoming and always looking for enthusiastic contributors.

Getting Started with Contributing

The first thing you need to do is identify a project that matches your interests and skill set. In this case, we are focusing on JavaScript, WordPress, and WPGraphQL, which are related to web development.

Next, look for active projects with regular updates, responsive maintainers, and welcoming communities. Check for the frequency of commits, issue resolution, and community engagement on forums and social media.

Familiarizing Yourself with the Project

Here are some steps you can take to familiarize yourself with the project you choose.

The main thing a project’s documentation tells you about it is its architecture, purpose, and processes. Read the documents and contribution guidelines to understand how to contribute effectively. Good documents also provide insights into the project’s governance, purpose, and processes.

The next thing to understand is the project codebase. You can do this by exploring the repository, reading the README.md and CONTRIBUTING.md files, and diving into the directory structure and any key components.

Once you do that, you can review open issues to identify areas where you can contribute.  Look for issues that are tagged with “good first issue” or “Need Help” as these are great opportunities to tackle for new contributors.

Best Practices for Contributing to OSS

There are multiple ways to contribute effectively with best practices in OSS.  Here are some for you to consider.

Effective Communication

Communication is a key practice in OSS contribution. You can do this by participating in chat channels, forums, mailing lists, and social media to stay informed about project updates. This will help you stay on top of ongoing changes and decisions and where the project is heading.

When you ask for help or provide feedback, use clear and respectful language. Be as specific as possible about your issue and provide context to make your point clearer and easier to understand.

You can also help others by answering questions, sharing your knowledge, and providing guidance. Your expertise can benefit other community members and foster a collaborative environment.

Quality Code

Quality code is a crucial part of overall best practice when contributing to OSS. Follow the project’s standards and guidelines to write maintainable and readable code. Consistent coding practices ensure that your contributions are compatible with the existing codebase.

Test your code to ensure software reliability. Write unit tests, integration tests, and end-to-end tests as appropriate to validate your changes.

Writing quality code includes detailed commit messages and pull request descriptions. These will help the maintainers review your changes. Clearly explain your changes, why they are necessary, and how they were implemented.

Review and Feedback Process

Understanding the review and feedback process is important for contributions to OSS. This involves familiarizing yourself with code reviews, responding to feedback constructively, and learning from the review process to improve your skills.

Familiarize Yourself with the Code Review Process: Start by examining past reviews to understand the maintainers’ criteria and expectations. This will give you insights into what maintainers look for in contributions and common areas for improvement. Observing how other contributions are reviewed can also provide valuable lessons.

Responding to Feedback: When you receive feedback on your contributions, be receptive and open-minded. Address the reviewers’ comments thoughtfully and make the necessary changes to improve your work. Constructive feedback is an opportunity for growth, so approach it with a positive attitude and a willingness to learn.

Learning from Reviews: Use the feedback from code reviews to enhance your skills and contribute more effectively. Each review is a learning opportunity that can help you write better code and understand best practices. Embrace the review process as a valuable part of your development journey, and apply the lessons learned to future contributions.

Conclusion

I hope this guide has given you a clear understanding of how to contribute to OSS projects. By following the steps and best practices outlined here, you’ll be well-prepared and excited to start contributing to projects like Faust.js, WPGraphQL, and WordPress. Your contributions will not only positively impact these communities but also help advance the software you use and care about.  As always, we look forward to hearing your feedback, thoughts, and projects so hit us up in our headless Discord!

The post Contributing to Open Source Projects appeared first on Builders.

]]>
https://wpengine.com/builders/contributing-to-open-source-projects/feed/ 0
Using Composer to Manage Plugins and Deploy to WP Engine https://wpengine.com/builders/using-composer-manage-plugins-deploy/ https://wpengine.com/builders/using-composer-manage-plugins-deploy/#respond Thu, 11 Jul 2024 18:24:08 +0000 https://wpengine.com/builders/?p=4931 Manage your WordPress dependencies with Composer and deploy to WP Engine with GitHub Actions.

The post Using Composer to Manage Plugins and Deploy to WP Engine appeared first on Builders.

]]>
We recently covered how to do branched deploys to WP Engine with GitHub Actions. Today, let’s explore managing plugin dependencies with Composer when deploying to WP Engine.

It helps if you are familiar with Composer, WPackagist, and Git version control. However, if you are not, here is an excellent resource to get you started: Managing your WordPress site with Git and Composer. Also, these instructions assume you have an existing WordPress site hosted on WP Engine that you are retroactively putting under version control.

Here is what we’ll be covering:

  • Version control (Git) – you will only need the wp-content/ directory under version control. We’ll let WP Engine maintain WordPress core automatic updates.
  • Composer—You will use Composer and WPackagist.org to manage WordPress plugins. Note that it will be your responsibility to manage plugin updates with this Composer setup, and utilizing Smart Plugin Manager or WordPress auto-updates is not covered.
    • Bonus: You will learn to install and manage ACF PRO as a Composer dependency.

Overview of project organization

Below is an example of your final GitHub repository. We will explore these in greater detail. (Also, check out the demo codebase on GitHub to follow along with the proposed structure.)

  • .github/workflows/[dev|staging|production].yml: These represent our GitHub Action configuration files for deploying our codebase to their corresponding environments. Be sure to become familiar with the WP Engine GitHub Action for Site Deployment, which relies on using rsync to sync the repository files with the targeted server.
  • rsync-config: These files configure our WP Engine GitHub Action for Site Deployment. The action relies on running a rsync between the GitHub repository and the targeted environment.
    • excludes.txt: Referenced in the .github/workflows/[dev|staging|production].yml file as the explicit rsync FLAGS. These are any items we want to exclude from being deleted each time our GitHub Action runs a rsync.
      • Hint: these files likely exist on the final WP Engine server and we do not want to remove them every time an rsync is executed in our GitHub Action.
    • includes.txt: Referenced in the .github/workflows/[dev|staging|production].yml GitHub Action as the explicit rsync FLAGS. These are any items we want to include in our GitHub Action rsync.
      • Hint: these will likely represent the un-ignored items in your project .gitignore which we’ll cover below.
  • bin/post-deploy.sh: This is how you pass any SCRIPTS to the GitHub Action to run commands on the final destination server.
    • Tip: you can run WP-CLI and Composer install commands on the final WP Engine environment.
  • plugins/: You will rely on Composer and WPackagist to install standard and stable plugins. However, we will also show you how you might handle a custom plugin.
    • plugins/demo-plugin: Represents any custom plugins you may want to version control. You could have as many of these as you like. For example, you could organize your custom functionality as plugins/foo-plugin, plugins/bar-plugin.
  • themes/: Similar to our plugins, you will likely version control a single theme for the final destination.
    • themes/demo-theme: Represents a single, custom theme you would have under version control.
  • .gitignore: It is critical to tell Git what you want to ignore from being under version control, as well as what you do not want to ignore (yes, this sounds odd, but trust us).
  • composer.json: Lists your project’s direct dependencies, as well as each dependency’s dependencies, and allows you to pin relative semantic versions for your dependencies.
  • composer.lock: Allows you to control when and how to update your dependencies.

Start by organizing a copy of your WordPress site’s wp-content/ directory to mirror the organization noted above. It is recommended to create this setup on your local computer. You can access a full site backup from WP Engine’s User Portal.  It is okay if there are other directories within your wp-content/ directory. You will tell Git what you want to ignore, or not ignore in the next step.

Create a .gitignore

Create a .gitignore file in your WordPress installation’s wp-content/ directory and place the code below:

.gitignore (full source)

#---------------------------
# WordPress general
#---------------------------
# Ignore the wp-content/index.php
/index.php

#---------------------------
# WordPress themes
#---------------------------
# Ignore all themes
/themes/*
# DO NOT ignore this theme!
!/themes/demo-theme

#---------------------------
# WordPress plugins
#---------------------------
# Ignore all plugins
/plugins/*
# DO NOT ignore this plugin!
!/plugins/demo-plugin

#---------------------------
# WP MU plugins: these are
# managed by the platform.
#---------------------------
/mu-plugins/

#---------------------------
# WP uploads directory
#---------------------------
/uploads/

#---------------------------
# WP upgrade files
#---------------------------
/upgrade/

#---------------------------
# Composer
#---------------------------
/vendor
auth.json
.env
.env.*
!.env.example

A few key things to note from the code above:

  • /plugins/*: this ignores any directories nested within the plugins/ directory.
    • !/plugins/demo-plugin: overrides the previous /plugins/* to allow the demo-plugin to not be ignored, and instead, it is version-controlled. 
  • /themes/*: this ignores any directories nested within the themes/ directory.
    • !/themes/demo-theme: overrides the previous /themes/* to allow the demo-theme to not be ignored, and instead it is version controlled. 

You can adjust the demo-plugin or demo-theme examples to work with your setup.

Set up Composer with WPackagist integration

Composer allows you to manage your PHP dependencies. WPackagist mirrors the WordPress plugin and theme directories as a Composer repository. 

Typically, you could consider utilizing Composer for PSR-4 / PSR-0 namespacing, linting, and unit testing. We’ll only focus on demonstrating how you might pull in some standard WordPress plugins. 

Here is a composer.json that installs a few example plugins from WPackagist: Two Factor, Gutenberg, and WordPress SEO. These are here for demonstration and feel free to replace them with plugins that are standard to your workflow.

composer.json (full source)

{
   "name": "wpe/composer-demo",
   "description": "Demo with Composer and deploy to WP Engine.",
   "license": "GPL-2.0+",
   "type": "project",
   "repositories": [
       {
           "type":"composer",
           "url":"https://wpackagist.org",
           "only": [
               "wpackagist-plugin/*",
               "wpackagist-theme/*"
           ]
       }
   ],
   "require": {
       "wpackagist-plugin/two-factor": "*",
       "wpackagist-plugin/gutenberg": "*",
       "wpackagist-plugin/wordpress-seo": "*"
   },
   "extra": {
       "installer-paths": {
           "plugins/{$name}/": [
               "type:wordpress-plugin"
           ],
           "themes/{$name}/": [
               "type:wordpress-theme"
           ]
       }
   },
   "config": {
       "allow-plugins": {
           "composer/installers": true
       }
   }
}

If you’re just integrating Composer into your project the first time then you’ll likely want to now run composer install after creating a composer.json like the one above. This will generate the corresponding composer.lock file for your project with these new dependencies (and their dependencies).

If this this is your first time integrating WPackagist into your existing Composer project then the key things to note from the code above:

  • Add the WPackagist repository under the repositories entry (see lines 6-15 in the code above).
  • Add any plugins or themes you want to install from WPackagist under the require key (see lines 17-19 in the code above). Be sure to use the wpackagist-plugin/ or wpackagist-theme/ prefixed vendor name to tell Composer that you intend these to be installed through WPackagist.
  • Set the installer-paths for your plugins and themes under the extra key to tell Composer where to install your WPackagist dependencies.

Run composer update to install the new required dependencies (see lines 22-29 in the code above).

How to install ACF PRO with Composer

ACF has some useful information on installing ACF PRO with Composer. We’ll use the composer.json code above as our starting point. Here are the steps you’ll need to set this up, which we’ll go over in further detail:

  1. Copy your ACF PRO license key from the Licenses tab. To activate your license via your wp-config.php file, add the following line to the file, replacing [key] with your license key: define( 'ACF_PRO_LICENSE', '[key]'.
  2. Add the ACF package repository to your composer.json.
  3. Install the plugin by running composer require wpengine/advanced-custom-fields-pro.

Here is what your final composer.json file will look:

composer.json (full source)

{
    "name": "wpe/composer-demo",
    "description": "Demo with Composer and deploy to WP Engine.",
    "license": "GPL-2.0+",
    "type": "project",
    "repositories": [
        {
            "type": "composer",
            "url": "https://connect.advancedcustomfields.com"
        },
        {
            "type":"composer",
            "url":"https://wpackagist.org",
            "only": [
                "wpackagist-plugin/*",
                "wpackagist-theme/*"
            ]
        }
    ],
    "require": {
        "wpackagist-plugin/two-factor": "*",
        "wpackagist-plugin/gutenberg": "*",
        "wpackagist-plugin/wordpress-seo": "*",
        "wpengine/advanced-custom-fields-pro": "^6.3"
    },
    "extra": {
        "installer-paths": {
            "plugins/{$name}/": [
                "type:wordpress-plugin"
            ],
            "themes/{$name}/": [
                "type:wordpress-theme"
            ]
        }
    },
    "config": {
        "allow-plugins": {
            "composer/installers": true
        }
    }
}

There are other ways to install and activate your ACF PRO license, so be sure to check out the full documentation. If you encounter any issues along the way, then send a support message.

Set up WP Engine GitHub Action for Composer integration

WP Engine’s GitHub Action for Site Deployment relies on rsync to transfer and synchronize local GitHub repository files to the final WP Engine hosting environment. This is critical to be mindful of when you initially setup your GitHub workflows.

Additionally, since we’re organizing the root of our repository within the wp-content/ directory then we want to be sure that we configure some key deployment options in the final workflow.

production.yml (full source)

# Deploy to WP Engine Production environment
# https://wpengine.com/support/environments/#About_Environments
name: Deploy to production
on:
  push:
    branches:
     - main
jobs:
  Deploy-to-WP-Engine-Production:
    runs-on: ubuntu-latest
    steps:
    - run: echo "Preparing to deploy to WP Engine production"
    - uses: actions/checkout@v3
    - name: GitHub Action Deploy to WP Engine
      uses: wpengine/github-action-wpe-site-deploy@v3
      with:
        # Deploy vars
        # https://github.com/wpengine/github-action-wpe-site-deploy?tab=readme-ov-file#environment-variables--secrets

        # The private RSA key you will save in the Github Secrets
        WPE_SSHG_KEY_PRIVATE: ${{ secrets.WPE_SSHG_KEY_PRIVATE }}
        # Destination to deploy to WPE
        # Change to your environment name
        WPE_ENV: yourEnvironmentName

        # Deploy options

        # An optional destination directory to deploy
        # to other than the WordPress root.
        REMOTE_PATH: "wp-content/"
        # Optional flags for the deployment
        FLAGS: -azvr --inplace --delete --include-from rsync-config/includes.txt --exclude=".*" --exclude-from rsync-config/excludes.txt
        # File containing custom scripts run after the rsync
        SCRIPT: wp-content/bin/post-deploy.sh

In the code above you’ll want to replace some of the deployment variables, like WPE_ENV and be sure to setup your SSH keys (both the WP Engine SSH Gateway key and your GitHub repository’s private SSH key: WPE_SSH_KEY_PRIVATE). Again, the helpful WP Engine step-by-step guide can help you here. The key options you will want to pay close attention to are listed in the table below.

NameTypeUsage
REMOTE_PATHstringOptional path to specify a directory destination to deploy to. Defaults to WordPress root directory on WP Engine. You want this to be wp-content/.
FLAGSstringSet optional rsync flags such as --delete or --exclude-from


Caution: Setting custom rsync flags replaces the default flags provided by this action. Consider also adding the -azvr flags as needed.
a preserves symbolic links, timestamps, user permissions and ownership.
z is for compression
v is for verbose output
r is for recursive directory scanning
SCRIPTstringRemote bash file to execute post-deploy. This can include WP_CLI commands for example. Path is relative to the WP root and file executes on remote. This file can be included in your repo, or be a persistent file that lives on your server.
Deployment options for Deploy WordPress to WP Engine GitHub Action (see full list).

You will want to pass some rather specific FLAGS and a custom post-deploy SCRIPT in order to get our targeted setup accurately deploying.

Configure rsync flags

You’ll be running rsync with the  --delete flag, which is destructive and we need to be careful about what we tell it to delete. Below is what you’ll want to put in your rsync-config/excludes.txt and rsync-config/includex.txt files.

excludes.txt (full source)

# Excluding these items from being deleted each rsync

plugins/*
themes/* 
mu-plugins/
uploads/
blogs.dir/
upgrade/*
backup-db/*
advanced-cache.php
wp-cache-config.php
cache/*
cache/supercache/*
index.php
mysql.sql

.env
.env.*
auth.json
vendor

includes.txt (full source)

# Including plugins/themes that we check into
# Git so that the version in GitHub is deployed

/plugins/demo-plugin
/themes/demo-theme

# ...other plugins could go here...

Create a post-deploy script

After everything is deployed, you will want to run composer install on the WP Engine environment. This will allow you to update your dependencies with Composer locally, commit any changes, push them to the Git remote, and once the GitHub Action is run to rsync any composer.json and composer.lock changes then it’ll install any updated dependencies on the final environment. This is the SCRIPT: wp-content/bin/post-deploy.sh we set in our GitHub Actions’s YML file (above).

post-deploy.sh (full source)

#!/bin/sh

echo "Starting post deploy script..."
echo "Switch directory to wp-content/"
cd wp-content
echo "Installing Composer dependencies..."
composer install --optimize-autoloader --no-dev --no-progress

Conclusion

Utilizing Composer with WPackagist to manage your WordPress plugin dependencies can help keep teams organized and facilitate consistent workflows.

Let us know how you’re maintaining your ideal workflow—tag us on X @wpengine.

The post Using Composer to Manage Plugins and Deploy to WP Engine appeared first on Builders.

]]>
https://wpengine.com/builders/using-composer-manage-plugins-deploy/feed/ 0
Request Headers in headless WordPress with Atlas https://wpengine.com/builders/request-headers-in-headless-wordpress-with-atlas/ https://wpengine.com/builders/request-headers-in-headless-wordpress-with-atlas/#respond Wed, 03 Jul 2024 19:04:05 +0000 https://wpengine.com/builders/?p=31655 Request headers are key-value pairs sent by the client to the server in an HTTP request. They provide additional information about the request, such as the client’s browser type, preferred […]

The post Request Headers in headless WordPress with Atlas appeared first on Builders.

]]>

Request headers are key-value pairs sent by the client to the server in an HTTP request. They provide additional information about the request, such as the client’s browser type, preferred language, and other relevant data. Request headers play an important role in enabling the server to understand and process the request appropriately.

In this article, I will guide you through how Atlas, WP Engine’s headless hosting platform automates request headers to your site.

Prerequisites

Before reading this article, you should have the following prerequisites checked off:

  • Basic knowledge of Next.js and Faust.js.
  • An Atlas account and environment set up.
  • Node.js and npm are installed on your local machine.

Request Headers in Atlas

The Atlas headless WordPress hosting platform automatically appends additional request headers to every request made to your site.  These headers are designed to provide valuable geographical and temporal information about the request origin, enabling you to tailor content and functionality based on the user’s location and local time.

The headers automatically appended are:

  • wpe-headless-country: The ISO alpha-2 country code of the request’s origin.
  • wpe-headless-region: The region within the country from where the request is made.
  • wpe-headless-timezone: The timezone of the request origin in TZ Database format.

Documentation on Atlas request headers is here.

Benefits of Geolocation Headers in Atlas

Geolocation headers offer several advantages:

  • Personalization: Tailor content and experiences based on the user’s location.
  • Localization: Display content in the user’s local language or relevant to their region.
  • Analytics: Gather insights into where your users are coming from to better understand your audience.
  • Compliance: Ensure compliance with regional regulations by adapting content accordingly.

This data has several use cases. You could display localized news and weather updates or promote things based on the user’s location. Moreover, you can make custom greetings based on the user’s local time and collect data on user distribution across regions and time zones for better insight and user experience.

Now that we understand request headers and how Atlas automates them, let’s implement an example of how to display an output of the request headers on a page.

Rendering Atlas Geolocation Headers in Next.js/Faust.js pages

For this example, we are going to use Next.js. The code and folder structure/file structure in the App Router Experimental package in Faust.js work exactly the same.

Since we are using Next 14 which defaults to React Server Components, we can fetch the request headers directly in the page component on the server side.

In the root of the App directory, create a folder called local and within that folder, create a file called page.jsx.  The structure should be: app/local/page.jsx.  Once you have created that, copy and paste this code block into the page.jsx file:

import { headers } from 'next/headers';

export default async function LocalPage() {
  const country = headers().get('wpe-headless-country') || 'No country data';
  const region = headers().get('wpe-headless-region') || 'No region data';
  const timezone = headers().get('wpe-headless-timezone') || 'No timezone data';

  return (
    <div>
      <h1>Geolocation Data</h1>
      <p>Country: {country}</p>
      <p>Region: {region}</p>
      <p>Timezone: {timezone}</p>
    </div>
  );
}


Let’s break down what the code is doing here.  At the top of the file, we import the headers function from the next/headers module. This will allow us to access the request headers in this server component.

Next, we define the component, calling it LocalPage. This is our async function that renders the page.

Following that, we retrieve the values of all the headers (country, region, timezone). If the headers are not present, the message defaults to stating that there is no data for that header.

Lastly we render the component returning the JSX.  The elements on the page will show the geolocation data.   

Once you have added this page file, make sure you push these changes up to your remote repository that is supported by Atlas before deployment.  GitHub, Bitbucket, and GitLab are the supported repos.

Deploying to Atlas

The last step is to connect your remote repo to Atlas, git push any changes, and visit the local page route we made to see the geolocation data. If you have not connected to Atlas yet, please do so. Here are the docs for reference.

Once you are deployed and have a live URL, you should have a page called /local that looks like this:

Conclusion

By leveraging request headers provided by WP Engine’s Atlas, you can enhance your headless WordPress applications with geolocation data, offer personalized and localized content, gather valuable analytics, and ensure compliance with regional regulations.

As always, we look forward to hearing your feedback, thoughts, and projects so hit us up in our headless Discord!

The post Request Headers in headless WordPress with Atlas appeared first on Builders.

]]>
https://wpengine.com/builders/request-headers-in-headless-wordpress-with-atlas/feed/ 0
Beta Testing WordPress with Local Blueprints https://wpengine.com/builders/beta-testing-wordpress-local-blueprints/ https://wpengine.com/builders/beta-testing-wordpress-local-blueprints/#respond Wed, 26 Jun 2024 14:53:08 +0000 https://wpengine.com/builders/?p=4810 Start testing the latest WordPress beta quickly with Local Blueprints.

The post Beta Testing WordPress with Local Blueprints appeared first on Builders.

]]>
A new release is on the horizon! 🌅

As with each release, there are countless hours of testing to ensure the overall experience is bug-free and optimized. WordPress 6.6 is targeted to be released on July 16, 2024. Right now, you can help by testing.

Local is the go-to tool to create a WordPress sandbox and effortlessly develop WordPress sites locally, and with Local you can get testing in seconds. Here are a few options to get you started.

Check out this video or continue reading to learn about all the ways to get testing.

Option 1: WP-CLI + Local

If you already have an existing site in Local then you can just upgrade it to the latest beta with WP-CLI. Here is how:

  1. Right-click on your site and choose ‘Open site shell’, which will open your system’s terminal application and automatically launch WP-CLI.
  2. Once WP-CLI is launched then just run this command: wp core update --version=6.6-RC1
Open WP-CLI in Local

Option 2: Local + WordPress Beta Tester plugin

If you already have a Local site then you can install the WordPress Beta Tester plugin and get the latest beta.

  1. Visit your WordPress dashboard’s Appearance > Plugins, and choose ‘Add New
  2. Search and install the WordPress Beta Tester plugin
  3. Once activated, visit the Tools > Beta Testing area and update the settings to get the latest beta (select the “Bleeding edge” channel and “Beta/RC Only” stream).
WordPress Beta Tester plugin settings screen

Option 3: Local Blueprint FTW!

Save a few clicks and just import our custom Local Blueprint, which comes with everything installed and ready for testing: WordPress Beta Tester plugin with WP 6.6 Beta 1 already installed and the default Twenty Twenty-Four theme activated.

Just click the download button below and drag and drop the downloaded WordPress-Beta-Tester_6.6-RC-1.zip into your Local app to spin up a new site and get testing!

Drag and drop Blueprint into Local

(Note: the super secret WordPress username and password for the Blueprint is admin.)

Reach out to @WPEBuilders and let us know how you’re using Local and what you’re testing in the latest WordPress 6.6 beta release.

The post Beta Testing WordPress with Local Blueprints appeared first on Builders.

]]>
https://wpengine.com/builders/beta-testing-wordpress-local-blueprints/feed/ 0
Best JavaScript Frameworks for Headless WordPress 2024 https://wpengine.com/builders/best-javascript-frameworks-for-headless-wordpress-2024/ https://wpengine.com/builders/best-javascript-frameworks-for-headless-wordpress-2024/#respond Thu, 13 Jun 2024 14:18:24 +0000 https://wpengine.com/builders/?p=31646 WordPress is widely recognized as a leading Content Management System (CMS), providing an excellent content authoring and editing experience. Meanwhile, building web experiences using JavaScript frameworks has never been more […]

The post Best JavaScript Frameworks for Headless WordPress 2024 appeared first on Builders.

]]>
WordPress is widely recognized as a leading Content Management System (CMS), providing an excellent content authoring and editing experience. Meanwhile, building web experiences using JavaScript frameworks has never been more popular and can provide more flexibility in the way pages are rendered, performance gains, enhanced security, and other capabilities. Thankfully, it’s possible to combine the two with a headless WordPress approach to get the best of both worlds.

In this article, we’ll explain the concept of headless WordPress and its advantages. We’ll also discuss key features to look for in a framework and present the top five frameworks to help you get started.

Headless WordPress Defined

Headless refers to a CMS that separates its backend content management (the “body”) from the frontend presentation layer (the “head”). In a typical WordPress setup, the backend includes the admin panel and content tools, while the front end is what visitors see.Many websites, like Taylor Swift’s Time Magazine Woman of the Year site, utilize WordPress as a headless CMS. This way, the WordPress dashboard can be used solely for content management while employing a different frontend stack for content display. The decoupled frontend and backend can “talk” to one another via the WPGraphQL plugin, which turns your WordPress install into a GraphQL server and allows it to interact with other applications. Alternatively, the WordPress REST API can be used for this purpose.

The Benefits of Using Headless WordPress

Using headless WordPress offers several advantages, including

Enhanced Performance: By decoupling the frontend from the backend, you allow WordPress to focus solely on the content database and API interactions. This setup can lead to faster load times and improved responsiveness, as the API-driven approach optimizes data delivery and reduces overhead.

Omnichannel Experiences: Without a single frontend, headless WordPress can seamlessly integrate with various platforms and technologies. This means you can publish and display content across multiple channels simultaneously, such as websites, mobile apps, and even digital kiosks, allowing for a unified and versatile content distribution strategy.

Improved Security: Headless setups, especially static sites, eliminate traditional backend vulnerabilities since there’s no exposed database. This significantly reduces the risk of common security threats associated with WordPress, such as SQL injection attacks, making your content safer from potential breaches.

It’s important to note that headless WordPress requires a solid understanding of web development. Additionally, managing and maintaining a headless setup can be more complex than a standard WordPress installation, as it involves handling both the content management system and the separate frontend technology stack.

Things To Consider with a JS Framework in 2024

Implementing headless WordPress can be complex, but frameworks provide the necessary tools to help developers efficiently build frontend platforms. While these frameworks are typically based on JavaScript, they also utilize CSS and HTML.

When selecting a framework, key features to consider include:

Static Site Generation (SSG): Ideal for creating static websites with pre-generated pages, SSG allows for faster loading times since HTML, CSS, JavaScript, and other assets are ready for the browser to consume immediately.

Server-Side Rendering (SSR): For scenarios where SSG isn’t feasible, SSR enables web pages to be rendered on the server before being sent to the user’s browser, enhancing performance and SEO.

Simple Data Fetching: Opt for frameworks that offer straightforward data fetching mechanisms to keep queries from your WordPress backend simple and efficient.

Minimal Configuration: Frameworks that require minimal setup and configuration can accelerate the development process, allowing you to focus on building your site rather than managing settings.

Core Web Vitals: Ensure the framework includes features that help optimize your site for Google’s Core Web Vitals, which measure page loading times, interactivity, and visual stability.

Considering these points will help you select a framework that best suits your needs. Each toolkit offers unique functionalities, and most frameworks have active online communities where you can seek support and advice.

Best Frameworks for Headless WordPress

1. Faust.js

Faust.js is a comprehensive framework built on top of Next.js designed for building frontend applications for headless WordPress sites. It aims to alleviate the challenges associated with headless WordPress development, providing a seamless and enjoyable experience for both developers and content creators.

Out of the box, Faust.js offers several essential features:

  • Post Previews: Allows content editors to preview posts before publishing, ensuring accuracy and consistency.
  • WP Template Hierarchy Replicated in JavaScript: Mirrors the familiar WordPress template hierarchy within a JavaScript environment, simplifying the transition for developers.
  • Authentication: Provides built-in authentication mechanisms, streamlining the process of managing user access and security.
  • Decoupled Blocks: Faust abstracts concepts like block discovery, customization, and rendering, working with WPGraphQL for Content blocks to query Gutenberg blocks.

These core features are crucial for any headless WordPress site and can be challenging to implement independently. Faust.js simplifies these tasks, enabling you to focus on building your site rather than configuring basic functionalities.

Furthermore, Faust.js integrates the Apollo Client GraphQL library. Utilizing Apollo Client with WPGraphQL in a headless WordPress setup can cache data and improve performance while providing an exceptional developer experience. This combination makes Faust.js a powerful tool for creating modern headless WordPress web applications.

Note that because Faust is built on top of Next.js, it benefits from all the features listed in the Next.js section below, as well.

2. Next.js

Next.js is a React framework for building full-stack web applications. You use React Components to build user interfaces, and Next.js for additional features and optimizations.  Under the hood, Next.js also abstracts and automatically configures tooling needed for React, like bundling, compiling, and more. This allows you to focus on building your application instead of spending time with configuration.

Key features of Next.js / App Router include:

Static Site Generation (SSG): Enables the creation of static pages that are pre-rendered at build time, leading to faster load times.

SEO Optimization: Next.js has a Metadata API that can be used to define your application metadata (e.g. meta and link tags inside your HTML head element) for improved SEO and web shareability.

Server-Side Rendering (SSR):  Provides the ability to render pages on the server for each request, ensuring up-to-date content and better performance for dynamic sites.

ISR: Incremental Static Regeneration, enables you to update static content without needing to rebuild your site completely. This feature is particularly useful for large websites with frequently changing content, ensuring that users always see the most current information without compromising performance.

API Routes: Allows the creation of serverless API endpoints within your Next.js application, simplifying the process of handling backend logic and data fetching.

File-Based Routing: Uses a file-system-based router, where folders and the files within are used to define your app’s routes.

3. Nuxt 

Nuxt is an open-source framework that makes web development intuitive and powerful.

Create performant and production-grade full-stack web apps and websites with confidence.

Key features of Nuxt.js include:

Universal Mode (SSR): has server-side rendering (SSR), enabling your application to render pages on the server before delivering them to the client. This improves SEO and performance, especially for dynamic content.

Static Site Generation (SSG): With Nuxt’s `nuxt generate` command, you can pre-render your site into static HTML. This is ideal for performance and security, as static sites are faster to load and less vulnerable to attacks.

Vue Components and Ecosystem: Leveraging the power of Vue.js, Nuxt.js allows you to build complex user interfaces with reusable components. The extensive Vue ecosystem, including Vuex for state management, enhances the development experience.

Automatic Code Splitting: Nuxt.js automatically splits your code by page, which optimizes loading times by only loading the necessary JavaScript for the current page.

Module System:  Nuxt.js boasts a robust module system, allowing easy integration of functionalities like PWA support, Google Analytics, and more. Modules simplify the addition of features without extensive configuration.

SEO-Friendly: Nuxt.js offers built-in support for meta tags and structured data, ensuring your site is optimized for search engines without requiring additional plugins.

File-Based Routing:  Nuxt.js uses a file-based routing system that mirrors your project’s directory structure, making it intuitive to define and manage routes.

4. SvelteKit

SvelteKit is an innovative framework built on Svelte, designed to provide a seamless development experience for building web applications. 

Key features of SvelteKit include:

  • Truly Reactive: SvelteKit leverages Svelte’s truly reactive nature, allowing for highly efficient and straightforward state management. This results in a more intuitive and performant development process compared to traditional frameworks.
  • Static Site Generation (SSG): SvelteKit supports static site generation, enabling you to pre-render your site at build time. This results in faster load times and improved SEO, as the static pages are optimized for performance and search engine indexing.
  • Server-Side Rendering (SSR): SvelteKit provides first-class support for server-side rendering, allowing pages to be rendered on the server and delivered to the client. This enhances performance and ensures that dynamic content is always up-to-date.
  • ISR: SvelteKit provides the performance and cost advantages of prerendered content with the flexibility of dynamically rendered content with support for ISR.
  • Simplified Data Fetching: SvelteKit streamlines data fetching through its built-in “load” functions. These functions allow you to fetch data at the page level, making it easy to manage and render data from your WordPress back end.
  • Routing and Navigation: SvelteKit features a file-based routing system, similar to Nuxt.js and Next.js, that simplifies route management. Additionally, SvelteKit provides client-side navigation for a smooth, SPA-like experience.
  • Hot Module Replacement (HMR): SvelteKit includes hot module replacement, which speeds up the development process by allowing you to see changes in real-time without a full page reload.
  • Progressive Enhancement: SvelteKit ensures that your application works even with JavaScript disabled, providing a basic but functional version of your site. This approach enhances accessibility and user experience across different devices and network conditions.
  • Built-In Adapters: SvelteKit supports various deployment targets through built-in adapters, such as Vercel, Netlify, and Cloudflare Workers. This simplifies the deployment process and allows you to choose the best hosting solution for your needs.

5. Astro

Astro is a modern, innovative framework designed for content-driven websites.

Key features of Astro include:

  • Islands Architecture: Astro introduces an “islands architecture,” where static content is pre-rendered by default, and JavaScript is only loaded for interactive components. This approach significantly enhances performance by reducing the amount of JavaScript that needs to be processed on the client side.
  • Static Site Generation (SSG): Astro excels at static site generation, enabling you to pre-render your entire site at build time. This results in extremely fast load times and improved SEO, as static pages are optimized for performance and search engine indexing.
  • Partial Hydration: With Astro’s partial hydration feature, only the necessary JavaScript for interactive components is loaded, further optimizing performance and user experience. This ensures that your site remains fast and responsive.
  • Framework Agnostic: Astro is framework-agnostic, allowing you to use components from Astro itself, React, Vue, Svelte, Solid, and more within the same project. This flexibility enables you to leverage the best tools for different parts of your application.
  • Simplified Data Fetching: Astro provides a straightforward data fetching mechanism, allowing you to easily pull data from your WordPress back end using WPGraphQL. This simplifies the process of integrating dynamic content into your static site.
  • Automatic Image Optimization: Astro includes built-in support for automatic image optimization, ensuring that images are served in the most efficient format and size. This further enhances performance and load times.
  • Markdown and MDX Support: Astro supports content authoring with Markdown and MDX, making it easy to create and manage content-rich pages. This feature is particularly useful for blogs and documentation sites.
  • File-Based Routing: Astro uses a file-based routing system that mirrors your project’s directory structure, simplifying route management and navigation.
  • SSR and Hybrid Rendering: While primarily focused on static site generation, Astro also supports server-side rendering (SSR) and hybrid rendering approaches. This allows you to combine the benefits of static and dynamic content as needed.
  • Built-In Integrations: Astro offers a wide range of built-in integrations, including support for popular CMSs, deployment platforms, and other tools. This extensibility makes it easy to add functionality and streamline your development workflow.

Where To Host

There are various platforms available for hosting your frontends and WordPress installations. However, the best-managed platform that provides optimized hosting for both your frontend and backend is WP Engine’s headless platform. It offers an all-in-one solution for building radically fast sites. WP Engine handles all the optimizations, configurations, CDNs, DevOps, git connections and more, ensuring your WordPress backend is always up to date and performing well.

 If you want to give it a try for yourself, please check it out here.

Summing It All Up

In conclusion, many of these frameworks share similar capabilities and features. Ultimately, the choice depends on your team and developers’ preferences for specific features and the development environment they enjoy working in. Additionally, consider the particular use cases for which you are building a headless WordPress application.

Whatever framework you decide to choose, remember that new JavaScript frameworks will continue to emerge, offering even more options. 🤣

But seriously, whatever you decide to go with, we would love to hear about your experiences and feedback with that particular framework using headless WordPress. So hit us up in our Discord and come join the headless stoke!

The post Best JavaScript Frameworks for Headless WordPress 2024 appeared first on Builders.

]]>
https://wpengine.com/builders/best-javascript-frameworks-for-headless-wordpress-2024/feed/ 0
ISR Support for Next.js/Faust.js  on WP Engine’s Atlas https://wpengine.com/builders/isr-support-for-next-js-faust-js-on-wp-engines-atlas/ https://wpengine.com/builders/isr-support-for-next-js-faust-js-on-wp-engines-atlas/#respond Mon, 03 Jun 2024 20:39:50 +0000 https://wpengine.com/builders/?p=31636 WP Engine’s Atlas is THE headless WordPress hosting platform.  In this article, I will discuss and guide you through the easy implementation of the latest feature on Atlas:  Support for […]

The post ISR Support for Next.js/Faust.js  on WP Engine’s Atlas appeared first on Builders.

]]>
WP Engine’s Atlas is THE headless WordPress hosting platform.  In this article, I will discuss and guide you through the easy implementation of the latest feature on Atlas:  Support for ISR on Next.js/Faust.js.  By the end of this article, you will have a better understanding of ISR and using Atlas to support it with Next.js/Faust.js

Prerequisites

Before reading this article, you should have the following prerequisites checked off:

  • Basic knowledge of Next.js and Faust.js.
  • An Atlas account and environment set up.
  • Node.js and npm are installed on your local machine.

If you do not and need a basic understanding of Next.js and Faust.js, please visit the docs:

https://nextjs.org/docs

https://faustjs.org/tutorial/get-started-with-faust

What is ISR?

Incremental Static Regeneration (ISR) is a feature introduced in Next.js that allows you to update static content after it has been deployed. Unlike traditional static site generation, which regenerates all pages at build time, ISR enables you to regenerate individual pages on a timed interval as new requests come in. This ensures that your site remains highly performant while still delivering up-to-date content to your users.

Why Use it in headless WordPress?

In headless WordPress, the front end is decoupled from the WordPress backend, often using Next.js and Faust.js to render the website. This architecture offers several advantages, such as improved performance, enhanced security, and greater flexibility in choosing front-end technologies.

However, one challenge with headless WordPress is ensuring that content changes in WordPress are reflected on the front end without sacrificing performance. This is where ISR becomes crucial. By leveraging ISR, you can achieve the following benefits:

Up-to-date Content: ISR allows your site to fetch the latest content updates from WordPress at specified intervals. For example, by setting a revalidation time of 60 seconds, Next.js will check for content updates every 60 seconds. When a user visits a page, the first user will receive stale content, but subsequent requests will serve the updated content, ensuring minimal delay in content updates.

Enhanced Performance: Since ISR updates only the specific pages that need regeneration at set intervals, your site remains fast and responsive. The initial load times are minimized, and only the changed content is updated, reducing the server load and build times.

SEO Benefits: Static pages are highly favored by search engines due to their speed and reliability. With ISR, you maintain the SEO advantages of static generation while ensuring that your content is always fresh and relevant.

Scalability: ISR enables your site to handle large volumes of content efficiently. Whether you’re running a blog with frequent updates or an e-commerce site with dynamic product listings, ISR ensures that your site scales seamlessly.

All those benefits got me stoked!  Let’s get it on our Next.js and Faust.js sites!

Configuring Next.js with Atlas ISR Support

Here are the docs link to the Atlas support for ISR.

In your Next.js project, go to your terminal and install the @wpengine/atlas-next package:

npm install --save @wpengine/atlas-next

This package provides improved support on Atlas.

Once you install it, ensure it is in your project by navigating to your package.json file at the root of your project:

"dependencies": {
   "@wpengine/atlas-next": "^1.1.0",
   "autoprefixer": "10.4.14",
   "eslint": "8.44.0",
   "eslint-config-next": "13.4.9",
   "next": "14.1.2",
   "postcss": "8.4.25",
   "react": "18.2.0",
   "react-dom": "18.2.0",
   "tailwindcss": "3.3.2"
 }

Now that you have verified the proper installation, staying at the root of your project,  modify your next.config.js file like so:

const { withAtlasConfig } = require("@wpengine/atlas-next");


/** @type {import('next').NextConfig} */
const nextConfig = {
 // Your existing Next.js config
};


module.exports = withAtlasConfig(nextConfig);

Faust.js Wrapper

If you are using Faust.js, all you need to do is modify your next.config.js file using the withFaust wrapper:

const { withFaust } = require("@faustwp/core")
const { withAtlasConfig } = require("@wpengine/atlas-next")

/** @type {import('next').NextConfig} */
const nextConfig = {
  // Your existing Next.js config
}

module.exports = withFaust(withAtlasConfig(nextConfig))

Next, we need to verify that it works.  Run your app in dev mode via npm run dev and you should see this output in your terminal:

Stoked!!! It works!!!

Atlas User Portal

We now have ISR set up with the proper configuration. The last steps are to connect our remote repository to Atlas, git push any changes, and observe ISR working in all its cache invalidation glory.

If you have not connected your local project to a remote repository, go ahead and do so.  Atlas supports GitHub, Bitbucket and GitLab.

Once you have connected your remote repository and added all your necessary environment variables, go ahead and build the app. If you have done this with an existing repo, you can git push the change, which will trigger a build.

When the application is finished in the build step, you are on the main page of the Atlas portal.  Navigate over to the Logs subpage:

In the Logs subpage, click the “Show logs” button on the Runtime option:

You should see the same output focusing on line 6 as you did in your terminal to ensure it’s working properly:

Awesome!!! It is implemented and working in runtime.  Now, when you edit or input new content in your WP backend, and then visit the live URL of the Atlas site you just deployed, the ISR should work on the timed interval you set it to like so:

Limitations

Just a note, the docs state that this feature is currently in the Beta phase, which entails:

  1. Functional completeness, offering comprehensive support for Next.js Incremental Static Regeneration.
  2. Ongoing assessment by Atlas Platform teams regarding the feature’s effect on website performance and application scalability.

Conclusion

Implementing Incremental Static Regeneration (ISR) with Next.js and Faust.js on WP Engine’s Atlas platform is a game-changer for maintaining performance and up-to-date content in a headless WordPress setup. By following the steps outlined in this guide, you can leverage ISR to ensure your site remains both fast and current, without the need for full rebuilds. 

The integration with Atlas also simplifies the deployment and management process, providing a seamless workflow from development to production. 
Get stoked on ISR and Atlas to deliver awesome user experiences and keep your site at the edge of web performance and content freshness.  As always, we look forward to hearing your feedback, thoughts, and projects so hit us up in our headless Discord!

The post ISR Support for Next.js/Faust.js  on WP Engine’s Atlas appeared first on Builders.

]]>
https://wpengine.com/builders/isr-support-for-next-js-faust-js-on-wp-engines-atlas/feed/ 0
5 Exciting (and Powerful) WordPress Features https://wpengine.com/builders/wordpress-features/ https://wpengine.com/builders/wordpress-features/#respond Wed, 29 May 2024 15:54:19 +0000 https://wpengine.com/builders/?p=31622 WordPress continues to evolve with various innovative features designed to enhance the user experience and streamline website development. From a revolutionized Font Library to intuitive site icon settings, these updates […]

The post 5 Exciting (and Powerful) WordPress Features appeared first on Builders.

]]>
WordPress continues to evolve with various innovative features designed to enhance the user experience and streamline website development. From a revolutionized Font Library to intuitive site icon settings, these updates cater to novice and experienced users.

WordPress patterns and the efficient List View in the block editor simplify content creation and management. Global Styles and the new theme.json configuration tool provide a unified approach to site customization.

This article explores five exciting WordPress features that enhance and elevate the website building experience for users and developers.

Google Fonts + WordPress: How to Install Them

With WordPress 6.5, the Font Library has transformed font management within the editor, making integrating fonts like Google Fonts easy. Users can now easily add any font from Google Fonts to their WordPress site, enhancing typography with minimal effort. This feature expands creative possibilities, incorporating various fonts into WordPress projects.

Add a Site Icon to Your WordPress Website

In WordPress 6.5, updating your site icon became more intuitive. Users can add or change the site icon directly from the General Settings panel. Navigate to Settings → General to update your site’s visual identity. This enhancement eliminates the need to use the Site Editor or Customizer for this task, making the experience smoother and more efficient.

Understanding List View in the WordPress Editor

The List View in the WordPress block editor is powerful for navigating through layers of content and nested blocks. In the Post and Page Editor or under Appearance > Editor, this feature allows easy selection and arrangement of blocks. It provides a clear, organized view of your content structure, making your editing experience more intuitive and efficient.

WordPress Patterns: How to Create, Edit and Utilize

WordPress patterns are like building blocks, ready to create stylish sections for your pages or posts. By inserting and customizing these patterns, you can quickly create complex layouts, saving you valuable time. Not only do patterns streamline the process, but they also showcase creative block combinations, enhancing your WordPress experience.

Getting Started with Global Styles in WordPress

Global Styles in WordPress simplify site-wide style changes without editing blocks or pages individually. This feature makes it easier for users and theme developers to apply consistent styling across blocks. Theme.json enhances this functionality, offering a unified approach to managing block settings and styles, streamlining the customization of WordPress sites.

The post 5 Exciting (and Powerful) WordPress Features appeared first on Builders.

]]>
https://wpengine.com/builders/wordpress-features/feed/ 0
The New WPGraphQL-IDE https://wpengine.com/builders/the-new-wpgraphql-ide/ https://wpengine.com/builders/the-new-wpgraphql-ide/#respond Mon, 20 May 2024 15:18:02 +0000 https://wpengine.com/builders/?p=31569 Whether you’re a seasoned developer or just starting out with WPGraphQL, you’re likely familiar with its user interface. Now, there’s an exciting update: a new plugin that transforms not just […]

The post The New WPGraphQL-IDE appeared first on Builders.

]]>
Whether you’re a seasoned developer or just starting out with WPGraphQL, you’re likely familiar with its user interface. Now, there’s an exciting update: a new plugin that transforms not just the UI’s look but also enriches it with additional features.

In this article, I’ll guide you through the latest WPGraphQL-IDE plugin, showcasing the enhanced visuals and new functionalities that elevate your experience with WPGraphQL.

Prerequisites

To benefit from this article, you should have experience using WPGraphQL, a WordPress install, and the WPGraphQL plugin installed. If you do not have a WordPress installation, consider using WP Engine’s headless sandbox.

Installation

To install the plugin, navigate to the GitHub repo and download the wpgraphql-ide.zip here

Once you download the plugin, go to your WP Admin and install and activate the plugin on the add new plugins page.  Once you have WPGraphQL and WPGraphQL-IDE installed, you are good to go.

The Old GraphiQL IDE

Before we take a deep dive into the new UI, let’s quickly go over the old one.  When downloading WPGraphQL, the default UI looks like this:

The old IDE features a classic white background. It uses a light color scheme that provides high contrast with dark text, which can be easier to read under certain lighting conditions but can get really hard on the eyes or glare over long periods. 

The layout has sections defined for the query composer, exposing all the data you have in WordPress, the query editor, and the response output. It also has a docs button to expose further documentation needed within the plugin, a history button that enables you to see your past created queries, and a button for screen enlargement.

The New WPGraphQL IDE

The new WPGraphQL IDE is a great addition for developers using WordPress with the WPGraphQL plugin. Its feature-rich and visually appealing interface significantly enhances the user experience.

Aesthetics 👨‍🎨

Upon downloading the WPGraphQL IDE plugin, you will notice you have an option at the top of your screen between the old and new versions:

The plugin allows you to choose between the two IDEs with a simple click. This comes in handy when you want to roll back to using the old version without having to do any heavy lifting.  In the next version, the WPGraphQL team will move this to the settings section so one is hidden and the other is exposed.

This is what the new version looks like when you click and choose it:

The first feature to notice is the new dark theme, which gets me super stoked!!! Utilizing shades of dark blue and gray, this theme is less straining on the eyes, particularly beneficial in low-light conditions. This makes it an excellent option for those spending extended hours coding. Moreover, dark mode not only reduces eye strain but also provides the interface with a modern and sleek appearance, significantly enhancing the aesthetic user experience.

The new IDE maintains a similar layout but improves visual separation through the use of color contrasts and shaded panels. This helps in distinguishing between different sections of the interface more clearly.

Enhanced typography with better spacing and font choices is implemented, contributing to a more pleasant visual and reading experience.

Features of the WPGraphQL IDE

The new features in the IDE are more stylized with great-looking icons and button designs.  Let’s dive into what they do and the capabilities of each.

All Access IDE Drawer 🚀

One convenient feature (And one of my favorites of this) the new WPGraphQL IDE contains is the IDE drawer.  You have access to the IDE on every page of the WP admin, the block editor UI, as well as the actual public-facing site.  All you need to do is just click on the rocket emoji 🚀 next to the GraphQL IDE option on the toolbar.   It is exposed anywhere the WP Admin bar is present.  This will get ya’ll stoke to not have to go back into the actual IDE page and just access it anywhere!

Here is a sample of the drawer being accessed on your frontend site:

Open Settings Dialog ⚙️

On the bottom left-hand corner of the IDE, you have a cog icon.  When clicked, it will reveal your settings:

The 3 settings you can control from this card are: 

  • Persist headers – This setting allows you to save custom HTTP headers across sessions. Turning it “On” will retain headers like authentication tokens when the IDE is reloaded. It’s recommended to use this feature only if you trust the device you’re working on, as retaining sensitive headers can pose a security risk if accessed by others.
  • Theme-This provides options to adjust the visual theme of the IDE interface to either match the system theme automatically or explicitly set it to a light or dark theme. This helps customize the look of the IDE according to your preference or environmental conditions (e.g., using dark mode at night to reduce eye strain).
  • Clear storage – This action removes all locally stored data in the IDE, such as cached responses, saved queries, and headers. It’s useful for starting fresh or troubleshooting issues related to corrupted or outdated local data.

Short Keys 🍏

When you click on the command icon, you will see a card with a cheat sheet for your short keys to shortcuts for certain functions.

Cmd + F: Search in editor—This shortcut opens a search input on the page, allowing you to type what you are looking for in the editor, as the image shows below.

Cmd + K: Search in documentation—This shortcut opens a search input when you are in the Docs pane, allowing you to quickly type and find the specific document you are looking for.

Cmd + Enter: Execute query—This shortcut allows you to execute the query you created in the query pane to get the JSON response.

Ctrl + Shift + P: Prettify editors—This shortcut allows you to automatically format the code written in the query editor to make it more readable and aesthetically pleasing. It ensures that your indentation, spacing, and line breaks are clean and enhances readability. The previous image shows a query that was prettified.  

Ctrl + Shift + M: Merge fragment definitions into operation definitions. In GraphQL, fragments are reusable pieces of query logic that can be included in multiple query or mutation operations. They help avoid redundancy in your codebase, making your queries easier to read and maintain.  

When you use this shortcut, the WPGraphQL IDE automatically integrates all the fragment definitions you have created into the main operation in which they are used. The merge will identify all fragments and integrate and merge these fragments directly into the operation’s definition, replacing the fragment spread with the actual definitions. This helps in viewing or debugging the operation as a single cohesive unit without the need to look up fragment definitions.

A sample fragment:


When using the shortcut, it will merge the PostFields fragment directly into your query, replacing the fragment spread with the actual defined fields in the fragment.

Ctrl + Shift + C: Copy query—This is a quick way to copy your query and paste it in your front end or wherever you want to paste it.

Ctrl + Shift + R: Re-fetch schema using introspection — A quick way to re-fetch the GraphQL IDE’s schema and keep it current.


Just a note, the Prettify, Copy, and Merge shortcuts also are available to you in the middle query pane as an icon pointed out in this image:

Notice the last icon, which is a link. This feature allows you to share the actual query document page with an authenticated user in your WP Admin. It’s awesome when collaborating with your team.

Re-fetch 🔄

When clicked, the refresh icon ensures that the GraphQL IDE’s schema always reflects the current state of the server schema. This aids accurate query development and troubleshooting by adding up-to-date changes to types, fields, or adjusted relationships.

Help 🆘

No, it’s not the Beatles’ fifth studio album (although it’s a great one!)… When clicked, it reveals a structured and comprehensive help menu designed to assist users at various levels of familiarity with WPGraphQL. From the beginner level all the way to joining the Discord server, it is a fast and convenient way to get the references you need for the level you are looking for.

GraphiQL Explorer 🗂️

The file icon, when clicked, reveals your explorer that exposes in a list format the array of WordPress-specific types and fields that can be queried via GraphQL.  This gets devs stoked by easily selecting them from this list and building out their queries much easier.

Docs 📘

When clicked, the book icon reveals the docs. This serves as a gateway to the documentation viewer within the IDE. This tool is essential for developers as it provides detailed insights and navigable descriptions of the GraphQL schema used within your WordPress setup. 

The documentation provides insights on root types, all schema types, detailed type information, and additional types. 

Conclusion

The WPGraphQL IDE plugin is a tool that enhances the developer experience when using and interfacing with its visuals and features. I touched on the plugin’s updated features. I encourage you to download the plugin and get stoked about its new look and capabilities!

There are more changes and updates to come. So as always stay tuned! We also would love to hear your feedback, thoughts, and projects you are doing in headless WordPress so hit us up in our Discord and the new WPGraphQL Discord!

The post The New WPGraphQL-IDE appeared first on Builders.

]]>
https://wpengine.com/builders/the-new-wpgraphql-ide/feed/ 0
Headless WordPress and Next.js 14: Core Competencies in App Router https://wpengine.com/builders/headless-wordpress-and-next-js-14-core-competencies-in-app-router/ https://wpengine.com/builders/headless-wordpress-and-next-js-14-core-competencies-in-app-router/#respond Mon, 22 Apr 2024 17:09:39 +0000 https://wpengine.com/builders/?p=31543 The App Router in Next.js 14 allows you to use React’s latest features, such as Server Components and Streaming. Combining this with headless WordPress can be daunting, especially with the […]

The post Headless WordPress and Next.js 14: Core Competencies in App Router appeared first on Builders.

]]>
The App Router in Next.js 14 allows you to use React’s latest features, such as Server Components and Streaming. Combining this with headless WordPress can be daunting, especially with the latest features within the framework and how the rendering methodology fits together in certain use cases.

In this article, I will guide you through a series of code challenges. I encourage you to try these yourself and if you get stuck, the answers are in the GitHub repository. At the end of this article and code challenge, you will gain knowledge of the core features in Next.js 14 using headless WordPress.

If you prefer the video format of this article, please access it here:

Pre-Requisite Knowledge

To get the most out of this article, you should have a basic understanding of HTML, CSS, React, and Next.js. If you need to brush up on your React skills, check out the React Foundations Course, which will introduce you to the fundamentals.

If you need to brush up on basic Next.js App Router methodology, please refer to my article here before reading this article.

The addition of the App Router to Next.js and the advent of React Server Components have ushered in a significant paradigm shift. In the past, devs using Next.js may have considered whole pages to be either SSG(Statically Generated), SSR(Rendered on the Server), or ISR(Incremental Static Regeneration).

Now, however, they’re most often thinking of their apps in terms of:

  • “Where should this render?” (server, client, or both)
  • “When should this render?” (build time, runtime, or stream whenever the server sends the response).

By the end of this, you’ll end up with your own Next.js 14 project that contains these pages:

  • /static-rendering
  • /dynamic-rendering
  • /streaming
  • /client-side-rendering

(A side note: I made a Navbar just to make it easier to navigate between pages, as you will see in the repo. However, you do not have to make one as you follow along since I will not go over the creation of one and the Next.js Link component.)

Here is the link to the finished repository for this article:

https://github.com/Fran-A-Dev/devrel-nextjs14-corecomp

Nested layouts and Partial rendering

Nested layouts are a new feature in the App Router. Let’s start with it.

Create a root layout that applies to the entire app. It should render this markup:

<!DOCTYPE html>
<html>
<head>
 <meta charset="UTF-8" />
 <title>DevRel Headless WP Core Competencies</title>
</head>
<body>
 <!-- Site content goes here -->
</body>
</html>

Replace <!-- Site content goes here --> with the children passed in.

Following that, create /dashboard/purchases and /dashboard/account routes with a simple div element rendered on each.

Once you have those finished, create a layout that applies to all routes nested under the /dashboard/.

It should render a sidebar that contains <Link /> components that point to the Purchases (/dashboard/purchases) and Account (/dashboard/account) pages.

Remember, if you get stuck during these challenges, you can refer to the finished repo. Here are links to the specific docs for this section:

https://nextjs.org/learn/dashboard-app/creating-layouts-and-pages

https://nextjs.org/learn/dashboard-app/navigating-between-pages

Image Component

Images are an important part of any website. In Next.js, its Image component extends the HTML <img> tag with features for auto-image optimization using a variety of props and configurations.

In this section, let’s utilize the image component to render an AVIF. An Avif is a powerful open-source, free file format that encodes AV1 bitstreams in the High Efficiency Image File Format (HEIF) container.

First, copy this image into your project:

https://videomentions.com/mic-and-headphones.avif

Then, on the Account page, render this image at the top using Next.js’ Image component. Make sure you specify the image and height to guard against Cumulative Layout Shift (CLS).

Below the image, render details and summary elements that display the following questions and their answers (it’s up to you to answer them 😊):

  • Does a simple <img> tag get rendered, or something else?
  • Is the primary image still in AVIF format, or something else?
  • Are srcset and sizes attributes defined to reference other sizes of this image? If so, explain how they work to serve responsive images.
  • Does the image leverage native lazy loading?

Inspect the image markup that gets rendered on the front end and take note of what you see.

The docs to this section: https://nextjs.org/learn/dashboard-app/optimizing-fonts-images#why-optimize-images

You should have something that looks like this now:

Server Components and Data Loading

React Server Components (RSCs)are components that allow you to write UI that can be rendered and optionally cached on the server side.  In Next.js 14 and its new App Router, the rendering work is further divided by route segments to enable streaming and partial rendering. The data loading is also done on the server.

Static Rendering

In this section, let’s utilize an RSC that does the data loading and rendering on the server. The goal is to create a full static page that can be cached on a CDN in a server component.

First, create a new /static-rendering route segment in the root of the App directory. Inside this route segment, include the declaration for a server component.

Then, await a fetch call to the /graphql endpoint associated with your headless WP backend to get the most recent 10 blog posts. Make a request for the databaseId, title, date and excerpt. Use raw fetch API for this and define the WPGraphQL requests in a template literal.

With the data returned, render a list of posts to the page. For good HTML semantics, represent each post as a <article> tag.

Time-Based Revalidation

This fully static page poses a problem, though. When a new blog post is published, this page will be out-of-date; it’ll still show the same list of posts that existed at the time it was generated.

Please use the stale-while-revalidate method here or SWR. The page should be invalidated once every 30 minutes to display accurate, fresh data. You can also test this out by doing a 10-second interval, changing your data in WordPress, then hitting your page again, waiting 10 seconds, then hitting it again. It should look like this:

The time-based method is great, but what if you have a use case where you need up-to-the-minute, close-to-real-time data? Next.js does have a way to do this. On-demand Revalidation allows you to invalidate your data on demand by path.

If you would like to add this method to the file instead of time-based, please free to do so. I left this method out of the repo. Currently, Atlas does not support on-demand revalidation but is working on adopting support for it soon!

Here are the docs for this section:

Static Rendering: https://nextjs.org/learn/dashboard-app/static-and-dynamic-rendering

Revalidation Techniques: https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data

https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#on-demand-revalidation

Dynamic Rendering

Dynamic Rendering or Server-Side Rendering is content rendered on the server for each user when the user visits the page at each request. This rendering method is beneficial if you need real-time data, user-specific content such as a dashboard, or access to information that can only be known at request time, such as cookies.

In this section, we will utilize this method to display relative date strings on a page, such as “Ten minutes ago,” “Three months ago,” etc.

First, create a new /dynamic-rendering route segment in the App directory. Copy your page component from the /static-rendering route and paste it in as the starting point for the /dynamic-rendering page component.

Next, use the unstable_noStore utility to opt out of static rendering and make the page dynamic (rendered on the server at request time). Docs: https://nextjs.org/docs/app/api-reference/functions/unstable_noStore

Let’s use the date-fns Use the NPM package to format dates as relative date strings (“Ten minutes ago,” “Three months ago,” etc.), as shown in this example.

If you have followed these steps correctly, you have now created a dynamic page that will always display up-to-date relative date strings to users. Stoked! It should look like this:

There are a few considerations in this section. Dynamism is costly since it requires more load on the server and is less performant. This is no longer a cacheable static page. It will hit the server on each request. Sometimes, though, it is worth it, depending on your use case. The date-fns library will not be included in the client-side bundle since this is being used server side.

Streaming and React Suspense

Streaming is a data transfer technique that allows you to break down a route into smaller “chunks” and progressively stream them from the server to the client as they become ready.

In this section, let’s use streaming to grab data from WPGraphQL and a random API endpoint that is not from WordPress. Docs:https://nextjs.org/learn/dashboard-app/streaming

The first thing we need to do is choose a random API endpoint. You can use any API endpoint that returns JSON data. For this example, I am going to use JSON server, an NPM package that allows you to run a local server and gives you an endpoint on whatever port you want to watch it at.

If you decide to use the JSON server method, you will need to create a file to house the JSON. For this article, I created a folder in the root of the project and just added my JSON there:

(Just a reminder, in choosing this method, you will need to run the command on another terminal to spin up the JSON server)

If you do not feel like using that, you can use any common one. I find the Rick and Morty GraphQL API to be a reliable one that many developers use. With this method, you can fetch the data right from the endpoint.

 Next, create a new route segment called /streaming. Copy the /dynamic-rendering page component into it as a starting point.

Remove the data fetching from the page component and add these two functions to the file:

https://gist.github.com/Fran-A-Dev/678ebe8a4e0affb80ab253402dcb88bc

Notice the “Simulate 3 seconds of network latency” line within the fetchStarWarsCharacters() function. This will be the data that will lag behind the WordPress data. Because this network latency exists, let’s opt for a streaming approach where we’re going to render our page immediately, show a loading placeholder, and then stream in the markup from these components when they’re ready using React Suspense.

Once that is all done, create a custom loading.jsx file within the root of the application and add whatever markup and style you want to it. When you create that file, import it into the page component of the streaming route segment and pass that into the Suspense component like this: <Suspense fallback={<Loading />}>

Ensure that within the page.jsx for this component, the post list, and characters list pop into the UI at the same time, regardless of which one took longer.

Stoked!!! We now have a page that loads as quickly as possible with the parts of the page that rely on more expensive queries being streamed in. It should look like this:

Client-Side Rendering

Client Components allow you to write interactive UI that is prerendered on the server and can use client JavaScript to run in the browser. Now, this was the default rendering method in React.js before server components. However, with Next.js 14, you now have to declare a component to be client-side with the "use client" directive in a file.

For this section, let’s build a dynamic page that grabs the github-username query string parameter in the URL, fetches that user’s public SSH key, and displays it on the page. This data fetching and rendering will take place entirely on the client– none of it on the server.

First, create a new /client-side-rendering route segment. Inside that route segment, create a simple page component that renders, then renders the <GitHubSSHKey /> component that we’ll create next.

Now, within this same route segment, create a GitHubSSHKey component. Include the "use-client" directive to mark it as a client component. Inside of this component, render the custom loading component we made in the previous section. Here are the docs: https://nextjs.org/docs/app/building-your-application/rendering/client-components

Following that, we need to access the value of the github-username query string parameter as described in the docs here. We can use the value of the github-username to make a fetch request like this to grab the user’s SSH key:

const response = await fetch(`https://github.com/${username}.keys`);
const sshKey = await response.text();

Once the request resolves, store the SSH key in state and trigger a re-render to replace your loading skeleton with this:

<h2>Public SSH key for {username}:</h2>
<p>{sshKey}</p>

Now, just add a query parameter to the URL with the github-username key and assign it the username and SSH key you want to grab. I used Kellen Mace’s.

Stoked!!! We have now implemented a client component. Something to keep in mind is that you can render a client component from a server component which we just did here. However, the other way around will not work. You can’t have a client component that renders a server component.

Conclusion

Next.js 14 is the latest version of the most used meta framework on top of React. It introduces new ways to handle data, create routes and files as well as rendering methods.  We hope you have a deeper understanding of how its core competencies work together.

Stay tuned for more Next.js 14 and headless WordPress content coming soon!!

As always, stoked to hear your feedback and any questions you might have on headless WordPress! Hit us up in our Discord!

The post Headless WordPress and Next.js 14: Core Competencies in App Router appeared first on Builders.

]]>
https://wpengine.com/builders/headless-wordpress-and-next-js-14-core-competencies-in-app-router/feed/ 0