Last active
January 29, 2023 13:42
-
-
Save marcelgruber/621e4e0422f311120768dc48f2dbbb5d to your computer and use it in GitHub Desktop.
NextJS Sitecore JSS Layout Service Response Shortcut URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This code makes it easier to ping your layout service without having to remember the long URL that is accessible by default. | |
// Add this file to /pages/api/viewpage or wherever you want. | |
// From there, all you need to do is visit /api/viewpage to view the layout service response for your home page | |
// Subpage would be /api/viewpage/someSubPage | |
// Note that this will be PUBLICLY VIEWABLE, so make sure to lock it down somehow, possibly with this or WAF rules: | |
// https://doc.sitecore.com/xp/en/developers/hd/200/sitecore-headless-development/walkthrough--creating-a-user-and-page-for-testing-sitecore-authentication.html | |
import type { NextApiRequest, NextApiResponse } from 'next'; | |
const handler = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => { | |
const apiHost = process.env.SITECORE_API_HOST | |
? process.env.SITECORE_API_HOST | |
: `https://mysite.sc`; | |
const siteName = process.env.NEXT_PUBLIC_JSS_SITE_NAME | |
? process.env.NEXT_PUBLIC_JSS_SITE_NAME | |
: `main`; | |
const apiKey = process.env.SITECORE_API_KEY | |
? process.env.SITECORE_API_KEY | |
: `{CHANGEME}`; | |
const { path } = req.query; | |
const itemPath = path ? path : '/'; | |
if (typeof itemPath === 'string') { | |
queryStringPath = itemPath; | |
} else { | |
queryStringPath = itemPath.join('/'); | |
} | |
const layoutServiceResponse = await fetch( | |
`${apiHost}/sitecore/api/layout/render/jss/?sc_lang=en&sc_site=${siteName}&sc_apikey=${apiKey}&item=${queryStringPath}` | |
); | |
res.status(200).json(await layoutServiceResponse.json()); | |
}; | |
export default handler; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment