Altis maintains the react-wp-ssr library which can be plugged into an existing React application to enable server-side rendering.
This guide will assume you're adding server-side rendering to an existing React-based theme using react-wp-scripts. Follow the Building a React app guide to set up a new theme, or consult the react-wp-ssr documentation for information about setting up react-wp-ssr with other projects.
To get started, add the JS library to your application:
npm install --save react-wp-ssr
In your application, replace the
ReactDOM.render call with a call to
import React from 'react'; import render from 'react-wp-ssr'; import App from './App'; render( () => <App /> );
You do not need to provide a root container ID, as this will provided by the PHP framework.
Enabling server-side rendering
To enable server-side rendering, first add react-wp-ssr to your project's Composer packages:
composer require humanmade/react-wp-ssr
Next, call the PHP API's
render function in your theme. This should replace the root container for your application. We recommend using a minimal
<?php get_header(); ReactWPSSR\render( get_stylesheet_directory() ); get_footer();
Your site should now render your application as before. In your browser's console, you should see a message from react-wp-ssr:
Skipping server-side render in development. Rendering in development may cause hydration errors, as the server renders from your built bundle, not from your development script. Add `define( 'SSR_DEBUG_ENABLE', true )` to your wp-config to enable in development
To test out server-side rendering, first ensure the built version of your application is up-to-date by rebuilding:
npm run build
Then add the constant to your configuration:
define( 'SSR_DEBUG_ENABLE', true ); // Optionally, set the following constant to `true` to disable loading the // script on the client. This will render a static site on the server only, // allowing you to verify server-side rendering is working correctly: define( 'SSR_DEBUG_SERVER_ONLY', false );
Refresh the page and view the page's source. You should see your application rendered statically into the HTML by the server.
react-wp-ssr comes with several limitations that you should be aware of. Most well-built applications will work without any modifications, but some applications may require modifications to adapt to these modifications.
For questions about adapting your application to server-side rendering, consult the Altis team.
Using v8js Directly
$v8 = new V8Js(); $result = $v8->executeString( '42 * 3.14;' );
Ensure that any custom code is heavily tested on development and staging environments before deploying to production.