iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more
To preview an unpublished WordPress post on a headless site, route WordPress’s Preview action to a protected endpoint on the frontend. That endpoint authenticates the request, enables preview state, resolves the post’s real frontend path, and redirects the browser there. The page then fetches draft data at request time and renders it with the same template used for published content. A public, cached API response by itself cannot display an unpublished draft.
What a headless WordPress preview must do
In a traditional WordPress installation, the Preview button and the page that renders the post live in the same application. A headless build separates those responsibilities: WordPress stores and edits the content, while a different application—often Next.js—renders the public website. Clicking Preview therefore has to cross an application boundary.
A reliable preview flow has four stages:
- WordPress starts the request. The editor’s Preview action uses a custom preview URL supplied by the integration or plugin.
- The frontend authenticates it. A shared secret, an authenticated editor session, or both are checked before preview state is enabled.
- The frontend resolves the destination. It determines the post, page, custom post type, language, and nested route from trusted WordPress data rather than blindly trusting a path supplied by the browser.
- The page fetches unpublished data. While preview state is active, the page uses a draft-capable REST or GraphQL request and renders the result dynamically. Normal visitors continue to receive published data.
Next.js calls this temporary state Draft Mode in the App Router. The Pages Router uses its preview-data mechanism. Both approaches bypass the normal prebuilt, published output for the current browser session; neither makes draft content public to unauthenticated visitors.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Before you implement preview
Confirm these decisions in the actual project. WordPress installations do not all expose the same preview setting or draft endpoint.
#1 Best Overall
- Powerful Turbo Fan:CAGIWIRU Electric Air Duster have reached speed up to 130000RPM,Can efficient remove dust and debris.With LED light and Three Adjustable Speed to meet with different cleaning tasks.
- With Attached USB C Fasting Charging cable.Charing 3 hours,Enjoy up to 240 minutes of use on the lowest setting, For third speed can use for 25mins.with four charging options to meet with your needs.
- Wide Application: attached 5 different nozzles,making it suitable for a variety of scenes, such as car,pet, pc, keyboards, and other electronic devices. It also serves for office and home clean duster.
- Handy Design & Portable:Cordless air duster electric nozzle is Light weight and small size, design and comfortable to hold and space saving, convenient to carry around. You can put it in your room or inside the car without taking up space.
- Economical &Reusable: Built durable materials with a long-lasting battery,our CAGIWIRU air duster it's a sustainable alternative to disposable air cans.
- Frontend router: identify whether the Next.js project uses the App Router or Pages Router. The documented implementations are different.
- Content API: choose the REST endpoint, GraphQL schema, or integration that can return unpublished content after authentication. A normal public request for a published post is insufficient.
- Identity and secret: decide whether the request is authorized with a CMS-to-frontend secret, an editor login, or an integration that combines both.
- Permalink map: document how a WordPress post ID, slug, custom post type, locale, and parent path become a frontend route. There is no universal mapping for every project.
- Cache behavior: make draft requests request-time and non-stale. Keep the ordinary public branch optimized for published content.
- Preview URL configuration: locate the custom preview-URL field in the selected WordPress plugin or integration. Its label, available variables, and security options vary by installation.
How to preview drafts with the Next.js App Router
The current App Router pattern has three parts: a route handler that enables Draft Mode, a WordPress custom preview URL that calls that handler, and page code that checks Draft Mode before choosing its data source.
1. Create a protected route handler
Put a route handler at a path such as /api/draft. The example below shows the control flow; adapt the parameter names and lookup query to your WordPress integration.
import { NextResponse } from "next/server";
import { draftMode } from "next/headers";
export async function GET(request) {
const url = new URL(request.url);
const secret = url.searchParams.get("secret");
const postId = url.searchParams.get("id");
if (!secret || secret !== process.env.WP_PREVIEW_SECRET) {
return new NextResponse("Unauthorized", { status: 401 });
}
if (!postId) {
return new NextResponse("Missing post identifier", { status: 400 });
}
// Resolve the route by querying trusted WordPress data.
const destination = await resolveFrontendPathFromWordPress(postId);
if (!destination) {
return new NextResponse("Content route not found", { status: 404 });
}
const draft = await draftMode();
draft.enable();
return NextResponse.redirect(new URL(destination, request.url));
}
The important security property is the destination lookup. Do not take a caller-supplied slug, redirect, or full URL and redirect to it without validation. Resolve the post’s canonical frontend path from WordPress data, then allow only paths your application recognizes. This prevents an open-redirect endpoint that could send an authenticated editor to an attacker-controlled site.
Keep WP_PREVIEW_SECRET in the server environment. Do not place it in a variable exposed to browser JavaScript, bundle it into client components, or commit it to source control. The WordPress integration and the frontend need the same secret, but site visitors do not.
2. Point WordPress Preview at the route
In the WordPress integration’s custom preview-URL setting, use the frontend origin and the protected route, passing the identifier and secret in the format that the integration supports. A conceptual shape is:
https://frontend.example/api/draft?id=POST_ID&secret=SERVER_SECRET
This is a pattern, not a universal WordPress setting. Some integrations provide a token variable, some send a post ID, and others send a slug or an encoded payload. Use the variables documented by the plugin or custom code installed on that site. The frontend must ultimately be able to identify the intended content and build its real route.
3. Branch page data fetching on Draft Mode
At the route that renders the post, check the preview state on every request. Use the draft-capable endpoint only when it is enabled.
Recommended Free Tools
Rank #2
- Screen Cleaner is Your Screen’s New Bestfriend! - EVEO is proud to present a screen cleaner that’s perfectly suited for your TV. Meet your new screen cleaner, computer screen cleaner, laptop cleaner, iPad cleaner, Macbook,tv cleaner or any other electronic device. Our screen cleaner spray and wipe along with the included plush microfiber cloth, easily removes dust, fingerprints & other smudges on the screen’s surface. Clean effectively for a streak-free screen
- Gentle on your Screens - Our screen cleaner spray and wipes is compatible to be used even for the most sensitive LCD, LED, CRT, and OLED screens in proper use. Be at ease knowing that this product is compatible with all the major brands: LG, SONY, Samsung, Sharp, iPad, iPhone, Android screens, Kindle, PC monitors - we’ve got you covered! Can be used as LCD screen cleaner, tv cleaner, smart tv screen cleaner, and more
- Premium Super Soft Plush Microfiber Cloth - Included in this efficient screen cleaning kit. This screen cleaner spray and wipe has our signature plush microfiber cloth specially designed to comply with screens and monitors and leave them streak-free. Has been shown to effectively absorbs stubborn stains, zero streaks, and no fiber shedding. Always use this together with our screen cleaner for the best results
- Easy-to-Use Screen Cleaner Kit + microfiber cleaning cloth - The EVEO Screen Cleaning Kit will easily be your new favorite tool when it comes to taking care of the things you love most, quick and easy solution for a streak-free screen. Simply screw on the sprayer gun on the screen cleaner bottle. Spray the cleaning liquid onto the microfiber cloth, then wipe the screen until desired cleanliness & shine is achieved.
- Quality Screen Care Kit Worth Purchasing - Enjoy a convenient Screen Cleaner anytime, anywhere you need it. Your satisfaction is our top priority. We stand behind the quality of our products and that’s why, you shouldn’t be worrying at all. We manufacture the Best Screen Cleaner. and can be used for laptop cleaning kit, laptop screen cleaner, tv screen cleaner for smart tv. MacBook screen cleaner, monitor cleaner or screen cleaner spray for electronic devices with microfiber cleaning cloth
import { draftMode } from "next/headers";
export default async function PostPage({ params }) {
const { isEnabled } = await draftMode();
const post = isEnabled
? await fetchDraftPost(params.slug)
: await fetchPublishedPost(params.slug);
if (!post) return notFound();
return <PostTemplate post={post} preview={isEnabled} />;
}
The published function can use your normal cache and static-generation strategy. The draft function must have a supported authenticated path to unpublished content and should avoid serving an old cached response. If the draft endpoint needs a WordPress credential, send it from server-side code only. Do not fetch draft content directly from a browser component with a privileged token.
After the handler enables Draft Mode, Next.js sets a bypass cookie for that browser. Requests carrying the cookie can render dynamically instead of reusing the prebuilt published result. A refresh should therefore show later edits as long as the draft request is not accidentally cached.
How to preview drafts with the Next.js Pages Router
The Pages Router uses a protected API route, preview data, and a redirect. The default preview session ends when the browser closes unless you configure a duration.
1. Protect the preview API route
export default async function preview(req, res) {
const { secret, id } = req.query;
if (secret !== process.env.WP_PREVIEW_SECRET) {
return res.status(401).json({ message: "Invalid token" });
}
if (!id) {
return res.status(400).json({ message: "Missing post identifier" });
}
const destination = await resolveFrontendPathFromWordPress(id);
if (!destination) {
return res.status(404).json({ message: "Content route not found" });
}
res.setPreviewData({ postId: id });
return res.redirect(307, destination);
}
Use a short, intentional preview-data lifetime when appropriate, and remember that a longer lifetime increases the period during which that browser remains in preview. The secret check must happen before setting preview data. Resolve and validate the destination before redirecting for the same open-redirect reason as in the App Router.
2. Make getStaticProps preview-aware
export async function getStaticProps(context) {
const { params, preview, previewData } = context;
const post = preview
? await fetchDraftPost(params.slug, previewData)
: await fetchPublishedPost(params.slug);
if (!post) {
return { notFound: true };
}
return {
props: { post, preview: Boolean(preview) },
...(preview ? {} : { revalidate: 60 })
};
}
The exact return shape can differ when using server-side rendering or another data layer, but the rule is constant: the preview branch must be selected from Next.js preview context and must call an endpoint that is authorized to return unpublished data. If both branches call the public published endpoint, the page will appear to ignore Preview even though the cookie is present.
Using Faust.js for a WordPress-specific Next.js integration
Faust.js is designed for Next.js frontends backed by WordPress. Its preview flow authenticates the request, checks whether the user can view the target content, and renders the draft through the same frontend template. Its tutorial passes an asPreview variable into a GraphQL query so the query can request the preview version.
Basic setup requires the WordPress backend URL and a Faust secret in the frontend environment, together with Faust, Apollo Client, and GraphQL packages. Package names, peer dependencies, and configuration can change, so match the current Faust documentation to the exact versions already used by the project rather than copying an old lockfile blindly.
Rank #3
- 【Large size】:Measuring 800 x 300 mm/ 31. 5×12 inches, which is wider and taller than others. Large mouse pad can perfectly fit your keyboard and mouse of any size, and there is also ample space for peripherals such as phones, tablets, etc.
- 【LED backlight mouse pad】:Blade Hawks RGB mouse pad provides 7 static modes and 7 dynamic modes will give you the options you are looking for. Power-off memory function remembers the last lighting mode you selected. The super glow fiber Chroma will give you a colorful gaming setup that you want.
- 【Anti-slip rubber base】:Made from Natural rubber, this gaming mousepad will firmly grip your desktop, allowing you to enjoy the ultimate precision in the games you are most passionate about. It also comes with a texture that enhances this ability even further.
- 【Smooth and waterproof surface】: Micro-textured cloth surface, for extremely precise mouse control and a smooth movement. When liquid splashes on the gaming mouse pad, it forms water droplets and slides down. Will not delay your work or gameplay.
- 【Plug and play】: This mouse and keyboard pad is powered by USB, plug and play, no driver required. One button control light modes. Press one time to change the lighting mode, press twice to change the brightness, press and hold about 3 seconds turn ON/OFF.
A typical Faust implementation still needs project-specific work:
- Configure the backend URL and secret as server-side environment values.
- Install the compatible Faust, Apollo Client, and GraphQL packages.
- Configure the WordPress side of the integration to send Preview requests to the Faust preview endpoint.
- Verify that the authenticated WordPress user has permission to view the requested draft.
- Ensure the GraphQL query receives the preview flag and that route resolution supports pages, custom post types, nested paths, and locales used by the site.
Faust.js supplies WordPress-oriented conventions; it does not remove the need to check your content model, capabilities, route map, and cache settings.
Getting unpublished content from WordPress
WordPress content has a status. The REST API post reference documents these common statuses:
| Status | Meaning for a headless preview |
|---|---|
publish |
Public content normally safe for the unauthenticated frontend. |
future |
Scheduled content that may require preview-aware authorization before its publication time. |
draft |
Unpublished working content; it must be requested through an authorized draft-capable API. |
pending |
Content awaiting review; access depends on the integration and the editor’s permissions. |
private |
Restricted content; do not assume a public frontend request may retrieve it. |
The REST reference documents retrieval of a post by ID with a path shaped like /wp/v2/posts/<id>. That endpoint’s availability for drafts depends on authentication and the WordPress configuration. The public, unauthenticated record is not automatically expanded to include draft or private content just because the frontend is headless.
WordPress core’s post_preview() behavior saves a draft or manual autosave for the purpose of showing a post preview. Your headless frontend must still have a supported way to receive that data. Depending on the integration, that may be an authenticated REST request, a GraphQL preview query, or an integration-specific endpoint. Confirm which mechanism your site actually exposes before writing the fetch function.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Build a dependable permalink and route resolver
Preview commonly fails when the content is found but the redirect points to the wrong frontend path. Maintain one resolver that understands every route type used by the site.
- Posts and pages: map the WordPress slug or ID to the corresponding frontend segment.
- Custom post types: include the type’s public base and any type-specific template.
- Nested pages: use the full parent hierarchy instead of assuming a single slug is globally unique.
- Languages: include the locale prefix or domain selected by the content record.
- Changed slugs: resolve from the current WordPress record, not a stale path copied into the preview request.
Return a 404 when the resolver cannot establish a valid internal path. Do not fall back to a caller-provided URL. A correct resolver also makes the preview route useful for editors: the browser opens the same URL structure that public visitors will use after publication.
Rank #4
- 【Softer and More Comfortable】Vaydeer wrist rest has unique diamond pattern, which is the combination of softness and aesthetics. The materials of wrist rest are improved into higher quality memory foam and covered with silky smooth lycra. The computer wrist rest makes you as comfortable and cushiony as like rest your wrists on clouds.
- 【Ergonomic Wrist Saver】The wrist rests for keyboard and mouse comes with a 17.32×3.15×0.83 inch keyboard wrist pad and a 5.94×3.15×0.83 inch mouse wrist support. Based on ergonomic design, the unique concave shape is the perfect fit for your wrist joints. The wrist rest pad fits most computer keyboards and laptops, improve hand and wrist posture, release your wrist and arm stress.
- 【Non-Slip Rubber Bottom】Featuring an anti-skid silicone base on the bottom, this wrist keyboard support stays firmly in place on your desk, preventing the padding from sliding around, ensuring stable and consistent wrist support during extended computer sessions.
- 【Better Experience & Pain Relief】Our keyboard arm rest is beneficial to alleviate the soreness caused by direct contact and friction between your arm and a hard desk surface, reducing the risk of wrist fatigue or carpal tunnel. The soft texture of memory foam can evenly distribute the pressure around your wrists and provide good support with just enough give.
- 【Helpful in Multiple Scenarios】Whether you're working, studying, writing, typing, gaming, this keyboard and mouse rest combo is an essential accessory to add comfort and support to your hands and wrists. It’s also a great gift for men, women, family, friend, coworker, gamer, teacher, etc.
Security requirements for a preview endpoint
A preview route is an authenticated bridge into unpublished content, not a convenience redirect. Apply all of these controls.
- Protect the secret: store it only in server-side environment configuration and in the CMS integration. Rotate it if it is exposed.
- Authenticate before enabling state: reject invalid or missing secrets before setting a cookie or preview session.
- Check capability: when the integration identifies a WordPress user, confirm that user can view the target post. Faust’s flow explicitly includes permission checking.
- Constrain redirects: derive the destination from trusted post data and allow only internal frontend paths.
- Limit draft fetching: select the draft endpoint only while preview state is active. Keep ordinary traffic on the published endpoint.
- Keep credentials server-side: privileged REST or GraphQL credentials must never be embedded in client-side JavaScript.
- Control caching: use request-time or otherwise explicitly uncached retrieval for drafts, and ensure a CDN does not cache a response containing unpublished content for public users.
- Log safely: record status codes, post identifiers, and route failures without writing secrets or draft bodies to logs.
Testing procedure for editors and developers
Use a draft that is not publicly published; testing only an already published post can hide a broken draft branch.
Free tools Windows power users keep installed
One-click scans. No signup required.
- Create or edit a WordPress draft with a distinctive title or paragraph that cannot be mistaken for the published version.
- Click Preview in WordPress and confirm that the browser leaves the WordPress backend for the expected frontend route.
- Inspect the response path and server logs, not the secret itself. A 401 indicates authentication; a 404 usually indicates identifier or route resolution.
- Verify that the rendered page contains the draft-only text and that the normal published page still shows the published version in a separate, non-preview browser.
- Change the draft, save it again, and refresh the preview. The new text should arrive through the request-time draft branch without publishing.
- Test a page, a custom post type, a nested route, and each supported language. Confirm that each resolves to the correct template.
- Close the browser or clear the preview state, then revisit the URL as a normal visitor. The unpublished content must not appear.
Troubleshooting common failures
Preview opens the WordPress backend
The custom preview URL is probably missing, malformed, or still points to the traditional WordPress site. Check the integration’s preview setting, frontend origin, route path, and variable names. Do not assume every WordPress plugin exposes the same field.
The frontend opens but shows the published post
Check the preview cookie or state first, then the page’s conditional branch. If preview state is enabled, inspect whether the draft function is actually called, whether it sends authentication, and whether a cache layer is returning the published response. Fetching the public post record in both branches cannot produce a draft preview.
The endpoint returns 401 or 403
Compare the CMS and frontend secrets without printing them. Confirm that the request reaches the expected environment, that server-side environment variables are loaded after deployment, and that the authenticated WordPress user has permission to view the post. For GraphQL integrations, check that the preview query and authentication headers are enabled together.
The endpoint returns 404 or redirects to the wrong route
Log the post identifier and the resolver’s chosen internal path. Check custom post type bases, parent pages, locale prefixes, and changed slugs. A resolver that handles only ordinary post slugs will fail on otherwise valid content.
Quick wins for a faster PC:
Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Preview is intermittently stale
Inspect every cache boundary: the WordPress response, the frontend fetch, Next.js static output, and any CDN. Draft requests should be request-time and bypass the published cache. In the App Router, verify that the request carries Draft Mode’s bypass cookie; in the Pages Router, verify that preview data has not expired.
Best Value
- 【No Drill Mounted】Cable management tray can be assembled in as little as 3 minutes or less-simply. Side clips easily clampe the edge of desk, pass through the holes on the sides, and secure excess cables with baskets. Desk cable management supports inward or outward installation to meet your needs in different scenarios, and provides you with great convenience when collecting and organizing wires.
- 【Rubber Pad Protects Desk】Wire organizer under desk built-in soft rubber pads on the clamp protect your desk from scratches, so you will not damage your furniture or office.
- 【Sturdy and Beautiful】Cord management under desk is made of high-quality carbon steel and holds about 15 lbs. The wire basket has 2 holes on each side of the tray to enable your cables to pass freely. Cable baskets are suitable for desk thickness use from 0.4" to 2.4".
- 【Space Saving & Keep Organized】Desk cable management tray holds all your power cords, outlet strips, USB hubs and computer transformers hidden from your feet, and the data cables will not enter the vacuum cleaner to keep your desk clean and tidy. Desk wire organizer is also suitable for use in the kitchen and outdoors.
- 【Reduce Safety Risks】Cable tray under desk keeps all plugs away from your kids, no more worry about tripping. Using 2 holes wire tray saves extra space, helps you easily cabling and wire protection. The mesh design is not easy to accumulate dust, but avoids safety accidents caused by messy wires.
Draft content leaks to ordinary visitors
Disable the draft branch unless preview state is positively verified. Review CDN cache keys and response headers, remove privileged credentials from client components, and test the URL in a clean browser with no preview cookie. Treat any leak as a security incident, not merely a rendering bug.
Choosing an implementation path
| Approach | Router or integration | Authentication model | Data layer | Best fit | Maintenance considerations |
|---|---|---|---|---|---|
| Custom Next.js Draft Mode | App Router | Protected route with a shared secret or editor authentication | REST or GraphQL, chosen by the project | Teams that want direct control over routing, security, and fetching | You own the route resolver, capability checks, API compatibility, and cache rules. |
| Custom Next.js preview data | Pages Router | Protected API route with a shared secret and preview session | REST or GraphQL, chosen by the project | Existing Pages Router applications | You must maintain preview-data lifetime, redirect handling, and the preview-aware data function. |
| Faust.js | Next.js WordPress integration | Authenticated preview flow with permission checks | GraphQL with an asPreview query variable |
Teams that prefer WordPress-specific conventions and packaged auth | Package compatibility and configuration are release-sensitive; route and content-model work remains project-specific. |
The available official guidance does not establish a universal performance or reliability winner. Choose based on the router already in use, the API your WordPress installation supports, the complexity of its permalink map, and how much integration code your team wants to own.
Questions editors usually ask
Can editors preview without publishing?
Yes. The authenticated preview request enables a temporary frontend state and retrieves the draft at request time. Publishing is not required, but the frontend must have an authorized draft-capable data request.
Does a headless preview make the draft publicly accessible?
No, when implemented correctly. Only the authenticated preview session uses the draft branch; ordinary requests continue to retrieve published content. Misconfigured caching or a missing preview-state check can defeat that separation.
Why are App Router and Pages Router instructions different?
They use different Next.js preview mechanisms. App Router uses Draft Mode and its bypass cookie; Pages Router uses preview data supplied to page data functions. Follow the pattern that matches the project rather than combining snippets from both.
Can the standard public WordPress REST request return my draft?
Not by default. Draft, pending, future, and private statuses require an authenticated and integration-supported request. The exact endpoint and credentials depend on the WordPress setup.
What should happen when a draft has no frontend route?
The preview endpoint should return a controlled not-found response rather than redirecting to an arbitrary path. Add the missing post type, parent hierarchy, locale, or slug rule to the trusted route resolver.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Clear out junk files and repair common Windows errors3Scan for outdated or missing drivers - takes under a minuteQuick Recap
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.

