Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk10 min

How to Use WordPress as a Headless CMS With SvelteKit

A practical, security-conscious guide to using WordPress for content and SvelteKit for the frontend, covering API choice, route loading, pagination, previews, rendering and deployment.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use WordPress for editing and content storage, and SvelteKit for every public page, route, template, and browser interaction. SvelteKit fetches WordPress data through the built-in REST API or the optional WPGraphQL plugin, then renders it with server-side rendering, prerendering, or client-side rendering according to each route’s needs. A reliable implementation keeps credentials and preview logic on the server, normalizes API responses in one module, maps WordPress slugs to SvelteKit routes, and chooses an adapter and cache strategy that match the deployment host.

What a headless WordPress and SvelteKit architecture looks like

In a headless setup, WordPress has no responsibility for the public presentation layer. Editors continue to create posts, pages, media, taxonomies, and custom content in WordPress. SvelteKit becomes the website visitors receive: it owns URL routing, layouts, components, metadata, rendering, navigation, and browser-side behavior.

As an Amazon Associate I earn from qualifying purchases.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The two applications communicate over HTTP. A SvelteKit server load function requests JSON from WordPress, converts that response into the shape a page needs, and returns it to a Svelte component. The browser can then navigate between pages using SvelteKit’s client-side transitions without reloading the entire document.

SvelteKit applications are server-rendered by default, then can transition to client-side navigation. That combination provides HTML for search engines and first-load performance while retaining the fluid behavior associated with single-page applications. You can selectively prerender stable routes or use client-side rendering for highly interactive areas.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

Responsibilities at a glance

Layer Primary responsibilities
WordPress Editorial UI, users and roles, posts, pages, media, taxonomies, custom post types, revisions and publishing workflow
API layer WordPress REST API or WPGraphQL schema, authentication, filtering, pagination and response data
SvelteKit Routes, layouts, templates, data loading, metadata, rendering mode, caching policy and interactive components
Hosting and delivery Node or another SvelteKit adapter, environment variables, build or runtime execution, CDN and cache behavior

REST API or WPGraphQL?

Both APIs can power the same SvelteKit site. The right choice depends on content relationships, query complexity and how much infrastructure your team wants to add.

Decision factor WordPress REST API WPGraphQL
Availability Included with WordPress core Requires the free, open-source WPGraphQL plugin
Request style Resource-oriented JSON endpoints such as /wp-json/wp/v2/posts POST requests containing a GraphQL query and variables, normally at /graphql
Field selection Endpoint responses and embedding determine the payload; normalize what you use Request an explicit field set in each query
Relationships Often require multiple requests or embedded resources Traverse related entities in one schema-defined query
Pagination Page and per-page parameters, with totals in response headers Relay-style connections using first and after cursors
Dependency and familiarity No additional plugin and familiar to WordPress developers Additional plugin and GraphQL schema knowledge
Best fit Simple blogs, brochure sites and projects aligned with WordPress core behavior Large content models, relationship-heavy pages and teams wanting a typed query contract

When REST is the practical starting point

The REST API exposes predictable, resource-oriented URLs and HTTP response codes. Core routes cover posts, pages, media, taxonomies, search and custom post types. A small site can begin without installing or maintaining another plugin, and developers can inspect endpoint responses directly in a browser or API client.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Start with REST when an archive needs posts and a detail page needs the post itself, featured media and basic taxonomy data. Its filtering and pagination parameters are sufficient for many editorial sites.

When WPGraphQL earns its place

WPGraphQL provides an extendable schema for WordPress. A page that combines an author, related posts, navigation, custom fields and taxonomy terms can request exactly those fields in one operation. Schema introspection and connection pagination give the frontend a consistent contract as the content model grows.

Use connection fields with first and after for archives. Keep the returned cursor and pass it to the next request rather than translating cursor pagination into guessed page numbers.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

This is an architectural recommendation based on the documented characteristics of each API, not a claim that one is universally faster. Measure response size, query complexity and cache behavior for your own content model.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Prepare WordPress as the content backend

  1. Define content types. Decide which information belongs in posts, pages, taxonomies, media or custom post types. Keep public content separate from internal editorial notes.
  2. Confirm API exposure. Publicly readable content is generally available anonymously. Private posts, password-protected content, internal users and protected metadata need authentication or explicit exposure rules.
  3. Choose the API. Use core REST routes for a straightforward model, or install and configure WPGraphQL when relationship traversal and selective fields justify the plugin.
  4. Record the origin. Your SvelteKit server needs the WordPress origin, for example https://cms.example.com. Keep the value free of a trailing path that would duplicate /wp-json or /graphql.
  5. Plan media and HTML. Decide whether WordPress supplies rendered HTML, whether the frontend transforms blocks, and which HTML elements are permitted after sanitization.

Set up the SvelteKit project and server-only configuration

Create a SvelteKit project using the version and adapter appropriate for your host. Put the WordPress origin in a private environment variable. In current SvelteKit projects, server code can read private runtime variables through $env/dynamic/private; follow the exact environment-variable module and adapter configuration required by the SvelteKit version you install.

// .env (never commit secrets)
WORDPRESS_URL=https://cms.example.com

Do not expose this value through a public environment module unless the origin is intentionally public and contains no credentials. Application passwords, bearer tokens and preview credentials must remain in server-only modules and must never be bundled into browser JavaScript.

Build a small API module instead of scattering fetch calls

Centralizing URL construction, error handling and response normalization makes it easier to change from REST to GraphQL or to add retries, logging and cache headers later.

// src/lib/server/wordpress.ts
import { env } from '$env/dynamic/private';

const origin = env.WORDPRESS_URL.replace(//$/, '');

export async function getPostBySlug(slug: string, fetchFn: typeof fetch) {
  const url = `${origin}/wp-json/wp/v2/posts?slug=${encodeURIComponent(slug)}&_embed`;
  const response = await fetchFn(url);
  if (!response.ok) {
    throw new Error(`WordPress returned ${response.status}`);
  }
  const posts = await response.json();
  return posts[0] ?? null;
}

The _embed parameter asks the REST API to include related resources such as featured media where available. Only pass through fields the page actually needs. Returning a small normalized object reduces coupling between WordPress response details and Svelte components.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord
  • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
  • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
  • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
  • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
  • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by

Fetch a post in a SvelteKit route

For a slug route such as src/routes/blog/[slug]/+page.server.ts, load the post on the server. The route can return a 404 when WordPress has no matching item and can keep authenticated requests away from the browser.

// src/routes/blog/[slug]/+page.server.ts
import { error } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';

export async function load({ params, fetch }) {
  const endpoint = `${env.WORDPRESS_URL}/wp-json/wp/v2/posts?slug=${encodeURIComponent(params.slug)}&_embed`;
  const response = await fetch(endpoint);

  if (!response.ok) {
    throw error(response.status, 'WordPress request failed');
  }

  const posts = await response.json();
  if (!posts.length) {
    throw error(404, 'Post not found');
  }

  return { post: posts[0] };
}

In the component, render the title, excerpt, content, featured image and metadata from the returned object. WordPress’s rendered content is HTML; apply the project’s sanitization policy before inserting it into the page. Never assume editor-entered HTML is safe merely because it came from your own CMS, particularly when multiple users or integrations can publish content.

Map WordPress identity to SvelteKit URLs

WordPress commonly identifies a post by its slug, while pages and custom post types may use a URI containing parent segments. Decide whether SvelteKit will reproduce WordPress’s URL structure or define a new one. If you change URLs, create redirects or a lookup layer so existing search results and inbound links do not become dead ends.

Query posts with WPGraphQL

GraphQL requests are ordinary server-side HTTP POST requests. The exact field names and filters depend on the installed schema and any custom types, so inspect the schema rather than assuming every WordPress field has the same name.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const query = `
  query PostBySlug($slug: ID!) {
    posts(where: { name: $slug }) {
      nodes { title content excerpt uri }
    }
  }
`;

const response = await fetch(`${WORDPRESS_URL}/graphql`, {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ query, variables: { slug } })
});

if (!response.ok) throw new Error('GraphQL transport failed');
const result = await response.json();
if (result.errors?.length) throw new Error('GraphQL query failed');

For an archive, request a connection with first and after. Return both nodes and page information, preserve the end cursor, and expose a “next” action only when the connection reports another page.

Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.

Implement archives, search and pagination

REST pagination

REST collection endpoints return a limited number of items by default. Supply pagination parameters such as page and per_page, and handle a request beyond the final page as an explicit condition rather than an unhandled exception. WordPress also provides total-item and total-page information in response headers; use those values to build reliable pagination controls.

const page = Number(url.searchParams.get('page') ?? '1');
const endpoint = `${origin}/wp-json/wp/v2/posts?page=${page}&per_page=12`;
const response = await fetch(endpoint);

if (response.status === 400) {
  throw error(404, 'Archive page does not exist');
}

const posts = await response.json();
const totalPages = Number(response.headers.get('X-WP-TotalPages') ?? '0');
return { posts, page, totalPages };

GraphQL cursor pagination

Cursor pagination avoids relying on offset page numbers when content changes between requests. Store the returned end cursor and use it as the next request’s after value. Keep the cursor in the URL or a form action if users need shareable “next page” states.

Search and taxonomies

REST provides search and taxonomy routes, while GraphQL exposes schema-specific connection fields. Normalize search results so the UI can display a title, URL, type and excerpt regardless of whether the result is a post, page or custom post type.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Handle authentication and previews safely

Anonymous requests are appropriate for public content. Use authenticated server requests for private material, protected metadata and editorial previews. Store application passwords, bearer tokens and preview credentials only in SvelteKit server modules or protected deployment secrets.

WPGraphQL preview flow

  1. Authenticate the preview request with a WordPress identity that can edit the target post.
  2. Send the X-GraphQL-Preview request header from the server-side SvelteKit code.
  3. Query the post through WPGraphQL. The preview response overlays the newest autosave while preserving the post’s identity.
  4. Render the result in a preview-only route that does not expose credentials to the browser.
  5. Mark the response private and bypass shared caches. WPGraphQL documents Cache-Control: no-store, private and Vary: X-GraphQL-Preview for preview requests.

Do not let a preview cookie or query parameter turn a public, cacheable URL into a cache-poisoning opportunity. Separate preview URLs, validate the user’s capability, and ensure your CDN does not cache authenticated responses.

Choose SSR, prerendering or CSR per route

Mode Use when Trade-offs
Server-side rendering Content changes frequently, requires request-time personalization or is important for SEO Requires runtime execution and a request-time WordPress dependency unless you add caching
Prerendering Content can be rebuilt at deploy time and does not need request-time data Very low runtime cost, but edits are not visible until a rebuild or invalidation
Client-side rendering The area is highly interactive and does not need server HTML for discovery More work happens in the browser and initial SEO or no-JavaScript behavior is weaker

A common arrangement is SSR for current news and previews, prerendering for stable documentation or marketing pages, and CSR for dashboards or interaction-heavy tools. The choice is per route, not a permanent verdict on the whole site.

Deploy SvelteKit with a headless WordPress backend

Build and run the SvelteKit application with the adapter required by the hosting platform. A Node adapter is a documented choice for some managed WordPress hosting environments, including the SvelteKit deployment path described by WP Engine. That path uses a repository-based deployment flow and recommends WPGraphQL Smart Cache for SvelteKit applications. Confirm the current host’s adapter, Node version, build command, runtime command and cache requirements before deploying.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Set WORDPRESS_URL and every authentication secret in the host’s server-side environment settings.
  2. Install the project dependencies and run the production build using the SvelteKit version’s documented command.
  3. Start the generated server with the adapter’s required command, or publish the generated assets when using a static deployment.
  4. Allow outbound requests from the SvelteKit runtime to the WordPress origin and configure CORS only when browser-side requests genuinely require it.
  5. Configure cache rules so public HTML can be cached according to freshness needs, while previews and authenticated responses remain private.
  6. Test canonical URLs, redirects, sitemap generation, image delivery, 404 behavior and a full editorial publish-to-page cycle.

Troubleshoot the failures that appear most often

Every request returns 404

  • Check that the origin is the WordPress site root and that the route includes /wp-json/wp/v2 for REST.
  • Verify the post is published and that the slug matches after URL decoding.
  • For GraphQL, confirm the plugin is active and the endpoint is enabled at /graphql.

The browser reports a CORS error

Move the request into a server load function or server route so the browser is not calling WordPress directly. If a browser request is intentional, configure the WordPress server to allow the exact frontend origin rather than using a wildcard with credentials.

Content is stale after publishing

Identify which layer cached the response: SvelteKit prerender output, a reverse proxy, a CDN, WordPress object caching or an API response cache. Use SSR for content that must appear immediately, rebuild prerendered pages after publication, or add an explicit invalidation mechanism.

Preview shows the published revision

  • Ensure the request is authenticated as a user who can edit the post.
  • Send X-GraphQL-Preview from server-side code, not client-side JavaScript.
  • Check that preview responses carry private, no-store cache headers and are not served from a shared cache.

Images or rich text break the layout

Inspect the actual media URL and HTML returned by WordPress, then normalize dimensions, responsive sources and allowed markup in one rendering layer. Do not blindly inject arbitrary HTML, and account for lazy-loading, missing alt text and embeds that depend on third-party scripts.

A production checklist

  • WordPress content types, taxonomies and URL rules are documented.
  • REST or WPGraphQL is selected for a stated reason.
  • API calls are centralized and return normalized data.
  • Server-only secrets are absent from public environment variables and client bundles.
  • Slug, URI, redirect and 404 behavior is tested for posts, pages and custom types.
  • REST page headers or GraphQL cursors drive archive pagination.
  • Rendered WordPress HTML is sanitized or transformed according to a defined policy.
  • Preview requests validate edit capability and bypass shared caching.
  • SSR, prerendering and CSR choices are made route by route.
  • The deployment adapter, Node version, build process and cache rules match the selected host.
  • Monitoring captures WordPress status failures, timeouts, malformed responses and publish-to-frontend delays.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.