WordPress, traditionally a server-side rendering platform, and Single Page Applications (SPAs) represent two different approaches to web development. Integrating these approaches requires thoughtful implementation of custom routing solutions. This post explores how to effectively bridge these technologies with the latest approaches in 2025.
Understanding the Challenge
WordPress uses a template hierarchy for routing while SPAs typically handle routing client-side with libraries like React Router or Vue Router. When combining these paradigms, we need solutions that allow them to work harmoniously.
WordPress REST API: The Foundation
The WordPress REST API provides the critical connection point for SPAs. Here’s how to register a custom endpoint:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// Register custom endpoint in functions.php add_action('rest_api_init', function () { register_rest_route('myapp/v1', '/custom-data', array( 'methods' => 'GET', 'callback' => 'get_custom_data', 'permission_callback' => '__return_true' )); }); function get_custom_data() { // Fetch and return custom data return array('status' => 'success', 'data' => 'Your custom data'); } |
With this foundation in place, let’s explore different approaches to integrating WordPress with SPAs.
Custom Route Solutions
1. WordPress as an API Backend (Headless WordPress)
This approach keeps WordPress and the SPA separate, using WordPress purely as a data source. According to the latest State of Headless 2024 report by WP Engine, this approach has seen widespread adoption among industry leaders.
Implementation Steps:
- Develop your SPA independently
- Use the WordPress REST API for data
- Deploy the SPA on a subdomain or separate domain
Example Setup:
- WordPress:
example.com
(CMS and API) - SPA:
app.example.com
(React/Vue/Angular application)
2. WordPress Theme Integration
This approach embeds your SPA within a WordPress theme:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Create a page template (spa-template.php) <?php /* Template Name: Single Page Application */ get_header(); ?> <div id="spa-root"></div> <script type="text/javascript"> var wpApiSettings = { root: '<?php echo esc_url_raw(rest_url()); ?>', nonce: '<?php echo wp_create_nonce('wp_rest'); ?>' }; </script> <?php get_footer(); ?> |
3. Custom Rewrite Rules
To handle SPA routes in WordPress:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Add to functions.php function spa_rewrite_rules() { add_rewrite_rule('^app/(.*)$', 'index.php?pagename=app', 'top'); } add_action('init', 'spa_rewrite_rules'); // Flush rewrite rules on theme activation function my_theme_activation() { spa_rewrite_rules(); flush_rewrite_rules(); } add_action('after_switch_theme', 'my_theme_activation'); |
WordPress Routing Plugins & Libraries
There are several excellent routing solutions available for WordPress. Here are the top options in 2025:
1. Brain\Cortex
An advanced routing system for WordPress using Symfony components:
- GitHub Repository
- Current version is actively maintained
- Uses the Symfony Routing Component for powerful pattern matching
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Brain\Cortex example use Brain\Cortex; add_action('cortex.routes', function(RouteCollectionInterface $routes) { $routes->addRoute('products', [ 'path' => '/products/{name}', 'handler' => 'My\Plugin\ProductController::show', 'requirements' => [ 'name' => '[a-zA-Z0-9\-]+' ] ]); }); |
2. Upstatement/routes
A lightweight routing solution inspired by Express.js:
- GitHub Repository
- Latest version 0.8.1 (stable)
- Simple and intuitive API for defining routes
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// Upstatement/routes example Routes::map('products/:name', function($params) { $product = new Product($params['name']); Routes::load('views/product.php', array('product' => $product)); }); // Add a route for a custom post type Routes::map('case-studies/:name', function($params) { $post = Timber::get_post_by_path('case-studies/'.$params['name']); Routes::load('views/single.php', array('post' => $post)); }); |
3. WP Emerge
A modern WordPress framework that includes routing:
- GitHub Repository
- Actively maintained with recent updates
- Full MVC implementation for WordPress
1 2 3 4 5 6 7 8 9 10 |
// WP Emerge routing example Route::get()->url( '/products/{name}' )->handle( 'ProductController@show' ); // Group routes with middleware Route::group()->middleware( 'AuthenticationMiddleware' )->routes( [ Route::get()->url( '/dashboard' )->handle( 'DashboardController@index' ), Route::post()->url( '/dashboard/save' )->handle( 'DashboardController@save' ), ] ); |
4. Rewrite Rules Inspector
A debugging tool for WordPress routes:
- WordPress Plugin Directory
- Essential for troubleshooting custom rewrite rules
5. WP REST API Routes
Extends the REST API with custom endpoints and routes:
- GitHub Repository
- Simplifies creating custom API endpoints
Composer Routing Libraries
For developers who prefer using Composer packages, these routing libraries integrate well with WordPress:
1. Symfony Routing Component
A powerful routing library that can be integrated with WordPress:
1 2 3 |
composer require symfony/routing |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
// Example integration use Symfony\Component\Routing\Route; use Symfony\Component\Routing\RouteCollection; use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\Matcher\UrlMatcher; // Set up routes $routes = new RouteCollection(); $routes->add('product', new Route('/product/{slug}', array( '_controller' => 'handleProduct' ))); // Match current request $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $parameters = $matcher->match($_SERVER['REQUEST_URI']); |
2. Laravel’s Illuminate Routing
Can be used standalone in WordPress:
1 2 3 |
composer require illuminate/routing illuminate/events |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
// Example in WordPress require_once 'vendor/autoload.php'; use Illuminate\Routing\Router; use Illuminate\Events\Dispatcher; use Illuminate\Container\Container; $container = new Container(); $events = new Dispatcher($container); $router = new Router($events, $container); $router->get('/api/custom', function() { return json_encode(['status' => 'success']); }); // Process the request add_action('template_redirect', function() use ($router) { $request = Illuminate\Http\Request::capture(); $response = $router->dispatch($request); // Output the response status_header($response->getStatusCode()); echo $response->getContent(); exit; }); |
3. FastRoute
A lightweight routing library by Nikita Popov:
1 2 3 |
composer require nikic/fast-route |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
// Example usage $dispatcher = FastRoute\simpleDispatcher(function(FastRoute\RouteCollector $r) { $r->addRoute('GET', '/blog/{id:\d+}', 'handler_blog_view'); $r->addRoute('POST', '/blog/{id:\d+}/comment', 'handler_blog_comment'); }); add_action('template_redirect', function() use ($dispatcher) { $httpMethod = $_SERVER['REQUEST_METHOD']; $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); $routeInfo = $dispatcher->dispatch($httpMethod, $uri); switch ($routeInfo[0]) { case FastRoute\Dispatcher::FOUND: call_user_func($routeInfo[1], $routeInfo[2]); exit; break; } }); |
Tools and Resources for Headless WordPress in 2025
- WP API Menus: Extends the WP REST API with menu routes
- WP REST API Controller: Customize endpoints
- Atlas Content Modeler: Custom content modeling for headless WordPress
- Headless WP Starter: Starter kit for headless WordPress
- WP Engine Atlas Platform: Managed hosting specialized for headless WordPress
Comparison of Routing Solutions
Solution | Complexity | Features | Best For | Maintenance Status |
---|---|---|---|---|
Brain\Cortex | High | Advanced pattern matching, middleware | Complex applications with many routes | Active |
Upstatement/routes | Low | Simple API, Timber integration | Simple projects, theme development | Stable |
WP Emerge | Medium | Full MVC, middleware | Modern WordPress applications | Active |
Symfony Routing | High | Complete routing system | Complex applications needing flexibility | Active |
Laravel Routing | Medium | Elegant API, middleware | Modern PHP developers familiar with Laravel | Active |
FastRoute | Low | Performance-focused | Projects needing simple, high-performance routing | Stable |
Headless WordPress Trends in 2025
According to the latest industry reports, there has been a significant increase in adoption of headless architecture among industry leaders. Key trends include:
- Composable Architecture: Breaking WordPress functionality into smaller, specialized services
- Jamstack Integration: Combining WordPress with Jamstack technologies for improved performance
- Framework Diversity: While React remains popular, Vue.js and Next.js have gained significant adoption
- Specialized Hosting: Providers offering tailored solutions for headless WordPress
- Performance Focus: Organizations prioritizing core web vitals and load times via headless approaches
Performance Considerations
When implementing custom routing solutions:
- Implement proper caching for API responses
- Consider server-side rendering for initial page loads
- Use code splitting to reduce bundle size
- Implement proper authentication for protected routes
- Utilize content delivery networks (CDNs) for static assets
Thoughts
Custom routing in WordPress and SPAs continues to evolve with better tooling and integration options. Whether you’re using more traditional WordPress with client-side enhancement or going fully headless, the ecosystem now offers mature and well-maintained solutions for every approach.
With the growing popularity of headless WordPress, there are now more specialized tools and hosting solutions designed specifically for this architecture. By leveraging the appropriate WordPress plugins or Composer libraries alongside the WordPress REST API, you can create powerful, dynamic web applications while maintaining the flexibility and content management capabilities that WordPress is known for.