Halloween 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 PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Draft Mode

How to Preview WordPress Content on a Headless Front End

By Freedom251 Team · · 14 min read

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

To preview an unpublished WordPress post on a headless site, WordPress must send the editor to a protected route on the front end instead of its own rendering layer. That route verifies a shared secret or the editor’s authenticated identity, determines the correct post and front-end URL, enables preview state, and redirects the browser. The front end then requests draft data at render time and uses the same component tree as the public page.

In Next.js, the implementation depends on the router. The App Router uses Draft Mode and a Route Handler; the Pages Router uses a protected API route and preview context. A WordPress-focused option such as Faust.js supplies authentication and preview conventions for a Next.js/GraphQL stack. In every approach, a normal public request must continue to read published data only.

As an Amazon Associate I earn from qualifying purchases.

What a headless WordPress preview actually does

In a traditional WordPress installation, the preview button can ask WordPress to render a draft through its own theme. A headless build separates those responsibilities: WordPress remains the content management system, while a separate application owns the public URL and templates. The preview button therefore needs a hand-off from the CMS to the front end.

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

The reliable sequence is:

  1. The editor clicks Preview in WordPress.
  2. WordPress calls a custom preview URL on the front end, including an identifier for the content and a secret or authenticated session.
  3. The front-end endpoint validates the request before enabling any preview capability.
  4. The endpoint resolves the destination from trusted post data, not from an arbitrary URL supplied by the caller.
  5. The browser receives a preview cookie or equivalent session state and is redirected to the post’s normal front-end path.
  6. The page detects preview mode and requests the draft, autosave, or otherwise unpublished representation through an API that permits that access.
  7. The page renders the draft with the same templates used for a published page.

Opening a published REST response and hoping it contains the draft is not a preview implementation. Draft, pending, future, and private records require an authenticated or otherwise authorized data request. The standard public API response must remain limited to content intended for anonymous visitors.

#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.

Choose the implementation path

Approach Preview entry point Draft-state mechanism Data layer Best fit
Next.js App Router Route Handler called by the CMS Next.js Draft Mode and its bypass cookie REST, GraphQL, or another authenticated endpoint Newer Next.js applications using the App Router
Next.js Pages Router Protected API route Preview context and a preview session REST, GraphQL, or another authenticated endpoint Existing Pages Router applications
Faust.js Faust’s WordPress preview flow Authenticated preview state GraphQL with preview variables such as asPreview Teams wanting WordPress-specific Next.js conventions

There is no documented universal winner for speed or reliability. The practical choice is usually architectural: own the integration with the general Next.js pattern, or adopt the WordPress-oriented authentication and query conventions provided by Faust.js. Package versions and setup details are release-sensitive, so match the official guide to the versions in your project.

Prerequisites before you configure preview

  • A WordPress site with a defined mapping from each content item to its front-end URL.
  • A headless application that can request unpublished content through an authenticated REST endpoint, GraphQL schema, or integration-specific API.
  • A secret shared between WordPress and the front end, or an editor authentication mechanism that the front end can verify.
  • A server-side environment variable for that secret. Do not expose it in browser JavaScript or a client bundle.
  • A clear policy for which roles and capabilities may preview which content.
  • Support for dynamic, request-time rendering while preview mode is active. A prebuilt static page cannot show an unsaved draft change by itself.

Decide how slugs, custom post types, nested paths, and language prefixes map between WordPress and the front end before writing the redirect. The consulted documentation does not define one universal permalink scheme; that mapping belongs to the individual project.

How to preview drafts with the Next.js App Router

1. Create a protected Route Handler

Add a route such as /api/draft (the exact path is yours) and have WordPress call it as its custom preview URL. The handler should accept the content identifier and the secret, validate both, and reject everything else. A simplified TypeScript shape is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { draftMode } from 'next/headers';
import { redirect } from 'next/navigation';

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const secret = searchParams.get('secret');
  const id = searchParams.get('id');

  if (secret !== process.env.WP_PREVIEW_SECRET || !id) {
    return new Response('Unauthorized', { status: 401 });
  }

  const post = await findPreviewablePost(id);
  if (!post || !canPreview(post)) {
    return new Response('Not found', { status: 404 });
  }

  const draft = await draftMode();
  draft.enable();
  redirect(frontendPathFor(post));
}

The example is deliberately conservative. findPreviewablePost and canPreview must use your authenticated WordPress integration; they cannot rely on an anonymous public response. The destination comes from the resolved post, so a caller cannot turn the endpoint into an open redirect by supplying an unrelated URL.

2. Configure WordPress to call that route

Set the WordPress integration’s custom preview URL to the route you created. The exact field name and token syntax vary by plugin or custom integration. Use a pattern that passes a post ID, slug, or another stable identifier plus the secret, for example:

https://frontend.example/api/draft?secret=SERVER_SIDE_VALUE&id=POST_ID

This is a shape, not a universal WordPress setting. Confirm how your installation substitutes the post identifier and whether it previews posts, pages, or custom post types through the same hook.

3. Read Draft Mode in the page

In an App Router page, call draftMode() and choose a draft-capable fetch only when it is enabled:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { draftMode } from 'next/headers';

export default async function PostPage({ params }) {
  const { isEnabled } = await draftMode();
  const post = await getPostByPath(params.slug, { preview: isEnabled });

  if (!post) return notFound();
  return <PostTemplate post={post} preview={isEnabled} />;
}

The preview branch should request the unpublished representation and pass the appropriate authentication to WordPress or your GraphQL service. The non-preview branch should continue to request published data. Keeping those branches explicit prevents an accidental leak of drafts to anonymous traffic.

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.

4. Ensure the response is dynamic

Draft Mode supplies a bypass cookie that allows a request to render dynamically rather than using prebuilt published output. Avoid forcing the preview page through a cache that was generated before the draft changed. If your data-fetching layer has its own cache, make its preview request uncached or otherwise keyed to the authenticated preview session.

5. Resolve the route from content, not a supplied slug

A slug supplied in a query string can be stale, malformed, or intentionally malicious. Resolve the post first, then derive its canonical front-end path from the same permalink rules used by the public site. This also handles changed slugs, custom post types, nested routes, and language segments more safely.

How to preview drafts with the Next.js Pages Router

1. Add a protected preview API route

The Pages Router pattern uses an API route that checks a shared secret, locates the post, enables preview mode, and redirects:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
export default async function handler(req, res) {
  const { secret, id } = req.query;

  if (secret !== process.env.WP_PREVIEW_SECRET || !id) {
    return res.status(401).end('Unauthorized');
  }

  const post = await findPreviewablePost(id);
  if (!post || !canPreview(post)) {
    return res.status(404).end('Not found');
  }

  res.setPreviewData({ postId: post.id });
  res.redirect(307, frontendPathFor(post));
}

Use the framework’s documented preview-session API for the Next.js version in your project. The default preview session ends when the browser closes unless a duration is configured. If you configure a longer duration, treat that as a deliberate security and editorial decision rather than a convenience setting.

2. Pass the preview context to data fetching

In getStaticProps, inspect the preview context and select the draft endpoint only for that request:

export async function getStaticProps({ params, preview = false, previewData }) {
  const post = await getPostByPath(params.slug, {
    preview,
    postId: previewData?.postId
  });

  if (!post) return { notFound: true };
  return { props: { post, preview } };
}

A Pages Router site may also use server-side rendering for the preview path. Whichever method you choose, the important boundary is the same: preview context authorizes a draft request, while a normal request reads published data.

3. Adapt the WordPress custom URL

WordPress installations and plugins expose different custom-preview-URL settings. Configure the CMS to call your API route with the secret and the identifier your handler expects. Do not assume that a URL documented for one plugin exists in another installation.

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

Using Faust.js for WordPress-oriented previews

Faust.js is built for Next.js front ends backed by WordPress. Its documented tutorial demonstrates an authenticated draft request, permission checking, and rendering through the normal front-end template. The GraphQL query receives an asPreview variable so the data layer can request the preview representation rather than the public post.

Rank #3
New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
  • [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

Basic configuration

The front end needs the WordPress backend URL and a Faust secret in server-side environment variables. A typical setup also includes Faust, Apollo Client, and GraphQL packages. Exact package versions and initialization APIs can change, so use the current Faust guide that matches your Next.js release instead of copying an old lockfile or tutorial verbatim.

Preview request flow

  1. WordPress sends the editor to the Faust preview endpoint.
  2. The endpoint authenticates the request and checks whether the user can view the target content.
  3. The front end establishes preview state and redirects to the resolved post URL.
  4. The page’s GraphQL query sets asPreview for that request.
  5. The returned draft is rendered by the same component used for the published page.

Faust.js does not remove the need to verify permissions or map permalinks. It packages those WordPress-specific conventions so the team does not have to design every piece from scratch.

What WordPress content can be previewed?

The WordPress REST API documents statuses including publish, future, draft, pending, and private. A post can be retrieved by ID through the documented shape /wp/v2/posts/<id>, but the public endpoint does not automatically make unpublished content available to an unauthenticated front end.

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 core post_preview() reference describes saving a draft or manually autosaving for the purpose of showing a post preview. In a headless architecture, that WordPress behavior still needs a delivery path: authenticated REST requests, a GraphQL schema with preview support, or an integration such as Faust.js. Which credentials and query fields are required depends on the site’s plugins, roles, custom post types, and API configuration.

Autosaves and unsaved editor changes

A preview may represent the saved draft or a manual autosave rather than the last published revision. Make sure the data API you call supports the kind of preview your editors expect. If it exposes only published records, the front end cannot display changes that have not been published.

Custom post types

For a custom post type, confirm all of the following in the actual project:

  • The type is exposed through the chosen REST or GraphQL API.
  • The preview request identifies the type as well as the item ID when IDs are not globally unique.
  • The resolver applies the correct capability check.
  • The permalink function produces the same nested or localized path used by the public site.
  • The front-end template exists for that type and handles preview-only fields safely.

Security rules that should not be optional

Keep secrets on the server

Store the preview secret in the WordPress integration and the front-end server environment. Never put it in a public environment variable, client-side bundle, HTML attribute, or browser-readable configuration file.

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

Authenticate before enabling preview

Check the secret or editor session before setting Draft Mode or preview cookies. With an authenticated WordPress integration, also verify that the user has permission to view the requested content. A valid identifier alone is not authorization.

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.

Prevent open redirects

Do not redirect to a path or URL copied blindly from the request. Resolve the post through trusted content data and generate the destination with your own routing function. This protects the preview endpoint from being used to send users to an unrelated site.

Keep public and preview data paths separate

The normal request must continue to read published content. Add a clear preview flag to the data layer and require it before requesting drafts. Logging should also avoid recording secrets or full authenticated request URLs.

Limit preview duration and scope

Use the shortest practical session lifetime. If editors need a long review session, configure that intentionally and provide a way to exit preview mode. Restrict preview capability to the roles that require it.

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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Why does the WordPress preview open the backend?

This usually means WordPress is still using its native preview URL or the custom URL was not saved in the integration that handles the editor’s post type. Check the preview URL generated for the specific post and verify that it reaches the front-end route, not a WordPress admin or public permalink.

If the URL reaches the front end but immediately returns to WordPress, inspect the shared secret, identifier substitution, and authentication check. A rejected request should produce a clear 401 or 404 response in server logs rather than silently redirecting.

Why does the front end show published or stale content?

  1. Confirm that the browser has entered preview state and received the Draft Mode or preview cookie.
  2. Confirm that the page reads the preview flag before choosing its data query.
  3. Inspect the request sent to WordPress or GraphQL and verify that it includes the credentials and preview variable required for unpublished data.
  4. Check application and CDN caches. A static page or cached API response can continue serving the published record even after preview state is enabled.
  5. Verify that the identifier maps to the intended revision, post type, language, and site.

These checks follow the documented flow: entry URL, authentication, preview state, redirect, and draft-capable fetch. Fix the earliest failed step instead of changing the template first.

How to test the complete workflow

Use a draft that is not publicly published and test the entire editor journey in an environment where the preview secret is configured.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Create or edit a draft in WordPress and save a distinctive change, such as a unique heading.
  2. Click Preview and record the URL that WordPress generates.
  3. Verify that the browser lands on the matching front-end path.
  4. Confirm in server logs that the request was authenticated and that preview state was enabled.
  5. Confirm that the page’s data request used the draft branch and returned the distinctive change.
  6. Change the draft again, refresh the preview, and verify that the new value appears without publishing.
  7. Open the same public URL in a separate session with no preview cookie and verify that unpublished text is not exposed.
  8. Test a missing post, an invalid secret, a changed slug, a custom post type, and a localized or nested route.

This procedure tests the integration rather than merely testing whether a page can be rendered with hard-coded preview data.

Comparison: which pattern should your team use?

Decision factor App Router Pages Router Faust.js
Framework surface Route Handler plus Draft Mode API route plus preview context Faust conventions on top of Next.js
Authentication You design and verify the secret or session You design and verify the secret or session WordPress-oriented authenticated flow
Draft query Your REST or GraphQL preview request Your REST or GraphQL preview request GraphQL query with preview variables such as asPreview
Routing responsibility Your resolver and permalink function Your resolver and permalink function Still requires project-specific permalink mapping
Static-output bypass Draft Mode cookie enables dynamic rendering Preview session supplies preview context Integration-specific preview state and query handling
Maintenance More integration code under your control Useful for established Pages Router sites Less WordPress plumbing, but dependency and version alignment matter

Choose the App Router pattern when the application already uses it and the team wants direct control over authentication, routing, and data fetching. Choose the Pages Router pattern when migrating an existing application is unnecessary. Choose Faust.js when its WordPress and GraphQL conventions match the project and the team accepts its dependency lifecycle.

FAQ

Can an unauthenticated browser request a WordPress draft through the public REST API?

Not by default. Draft and private content require an authenticated, permission-aware request or a purposely configured integration. Exposing the public published endpoint does not grant draft access.

Does enabling preview mode publish the post?

No. Preview state changes how the front end fetches and renders content for an authorized session. The post remains in its existing WordPress status until an editor publishes it.

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

Should every post type use the same preview route?

It can, provided the route receives enough information to identify the type and item and your resolver applies the right capability and permalink rules. Some integrations use separate routes or query shapes for custom post types.

Why does a preview work once and then disappear?

Check the preview-session lifetime and cookie settings. The Pages Router’s documented default session ends when the browser closes unless a duration is configured; an App Router Draft Mode cookie can likewise be removed when preview is disabled or the session is cleared.

Final implementation checklist

  • WordPress sends Preview to a protected front-end endpoint.
  • The endpoint verifies a server-side secret or authenticated editor identity.
  • The requested post is resolved before the redirect destination is generated.
  • Draft Mode or preview context is enabled only after authentication and permission checks.
  • The page requests unpublished data only when preview state is active.
  • Anonymous requests continue to receive published data.
  • REST or GraphQL credentials and preview fields match the project’s actual integration.
  • Post types, slugs, nested paths, and language routes map correctly.
  • Static and CDN caches cannot replace an authorized request with stale published output.
  • A draft update is visible after refresh without publishing, while the public URL remains unchanged.

A headless preview is therefore a small authenticated application flow, not a special template. Once WordPress can reach the front end, the front end can prove the editor is allowed to preview, and the data layer can request the unpublished representation, editors can review drafts through the real production template without exposing those drafts to ordinary visitors.

Frequently Asked Questions

Can an unauthenticated browser request a WordPress draft through the public REST API?

Not by default. Draft and private content require an authenticated, permission-aware request or a purposely configured integration. Exposing the public published endpoint does not grant draft access.

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

Does enabling preview mode publish the post?

No. Preview state changes how the front end fetches and renders content for an authorized session. The post remains in its existing WordPress status until an editor publishes it.

Should every post type use the same preview route?

It can, provided the route receives enough information to identify the type and item and your resolver applies the right capability and permalink rules. Some integrations use separate routes or query shapes for custom post types.

Why does a preview work once and then disappear?

Check the preview-session lifetime and cookie settings. The Pages Router’s documented default session ends when the browser closes unless a duration is configured; an App Router Draft Mode cookie can likewise be removed when preview is disabled or the session is cleared.

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.

Draft ModeFaust.jsGraphQLheadless CMSNext.jsPreviewREST APIWordPress

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.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.