Skip to content

Commit

Permalink
Move preview route and update usages of nextjs-adapter methods #773
Browse files Browse the repository at this point in the history
  • Loading branch information
pmi committed Jan 31, 2024
1 parent d5db04b commit 31eb6c3
Show file tree
Hide file tree
Showing 20 changed files with 79 additions and 459 deletions.
1 change: 0 additions & 1 deletion next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
2 changes: 1 addition & 1 deletion next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ async function getEnonicHeaders() {

const config = {
reactStrictMode: true,
trailingSlash: true,
trailingSlash: false,
transpilePackages: ['@enonic/nextjs-adapter'],
webpack: getEnonicWebpackConfig,
headers: getEnonicHeaders,
Expand Down
44 changes: 0 additions & 44 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 0 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,14 @@
"lint": "next lint"
},
"dependencies": {
"@formatjs/intl-localematcher": "^0.5.2",
"cross-env": "^7.0.3",
"html-react-parser": "^5.0.3",
"negotiator": "^0.6.3",
"next": "^14.0.3",
"react": "18.2.0",
"react-dom": "18.2.0",
"unescape": "^1.0.1"
},
"devDependencies": {
"@types/negotiator": "^0.6.3",
"@types/node": "^20.8.9",
"@types/react": "18.2.33",
"@types/react-dom": "^18.2.14",
Expand Down
45 changes: 0 additions & 45 deletions src/apiold/preview.ts

This file was deleted.

52 changes: 0 additions & 52 deletions src/apiold/revalidate.ts

This file was deleted.

10 changes: 5 additions & 5 deletions src/app/[locale]/[[...contentPath]]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ export type LayoutProps = {
children: ReactNode
}

export default async function ContentLayout(props: LayoutProps) {
export default async function ContentLayout({params, children}: LayoutProps) {

const {meta, common} = await fetchContent(props.params.contentPath)
const {meta, common} = await fetchContent(params);

return (<>
<Header meta={meta} title={common?.get?.displayName} logoUrl={getUrl('/images/xp-shield.svg', meta)}/>
Expand All @@ -21,16 +21,16 @@ export default async function ContentLayout(props: LayoutProps) {
maxWidth: 960,
padding: `0 1rem`,
}}>
{props.children}
{children}
</main>
<Footer/>
</>
)
}

export async function generateMetadata(props: LayoutProps, parent: ResolvingMetadata): Promise<Metadata> {
export async function generateMetadata({params}: LayoutProps, parent: ResolvingMetadata): Promise<Metadata> {

const {common} = await fetchContent(props.params.contentPath)
const {common} = await fetchContent(params);

return {
title: common?.get?.displayName || 'Content path layout',
Expand Down
21 changes: 6 additions & 15 deletions src/app/[locale]/[[...contentPath]]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React from 'react';
import {ContentPathItem, fetchContent, fetchContentPathsForAllLocales, FetchContentResult} from "@enonic/nextjs-adapter";
import {fetchContent, fetchContentPathsForAllLocales, FetchContentResult} from "@enonic/nextjs-adapter";
import MainView from '@enonic/nextjs-adapter/views/MainView';

import "@enonic/nextjs-adapter/baseMappings";
import "../../../components/_mappings";
import {notFound} from 'next/navigation';
import {draftMode} from 'next/headers';

export const dynamic = 'auto'
export const dynamicParams = false // show 404 for missing in cache pages
Expand All @@ -22,25 +22,16 @@ export type PageProps = {
}

export default async function Page({params}: { params: PageProps }) {
console.info('Accessing page', params);
const {isEnabled: draft} = draftMode();
console.info(`Accessing page${draft ? ' (draft)' : ''}`, params);

const data: FetchContentResult = await fetchContent(params.contentPath)

if (data.error?.code === '404') {
notFound();
}
const data: FetchContentResult = await fetchContent(params);

return (
<MainView {...data}/>
)
};

export async function generateStaticParams(props: { params: PageProps }): Promise<any[]> {
const paths = await fetchContentPathsForAllLocales('\${site}/');
const result = paths.map((item: ContentPathItem) => ({
contentPath: item.params.contentPath,
locale: item.locale,
}));
console.info('Content path layout paths: ', result);
return result;
return await fetchContentPathsForAllLocales('\${site}/');
}
53 changes: 53 additions & 0 deletions src/app/api/preview/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {NextRequest, NextResponse} from 'next/server';
import {redirect} from 'next/navigation';
import {draftMode} from 'next/headers';

export function HEAD(req: NextRequest) {
return processRequest(req);
}

export function GET(req: NextRequest) {
return processRequest(req);
}

function processRequest(req: NextRequest) {
const params = req.nextUrl.searchParams;

const token = params.get('token');
let response = validateToken(token);
if (response !== null) {
return response;
}

const path = params.get('path');
response = validatePath(path);
if (response !== null) {
return response;
}

console.info(`Previewing [${path}]...`);

draftMode().enable();

redirect(!path?.length ? '/' : path);
}

function validateToken(token: string | null) {
if (token !== process.env.ENONIC_API_TOKEN) {
// XP hijacks 401 to show login page, so send 407 instead
return NextResponse.json({message: 'Invalid token'}, {
status: 407,
});
}
return null;
}

function validatePath(path: string | string[] | null) {
// If the slug doesn't exist prevent preview mode from being enabled
if (path === null || path === undefined) {
return NextResponse.json({message: 'Invalid path'}, {
status: 400,
});
}
return null;
}
4 changes: 3 additions & 1 deletion src/app/api/revalidate/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import {revalidatePath} from 'next/cache';
import {NextRequest} from 'next/server';
import {getProjectLocales} from '@enonic/nextjs-adapter';

const LOCALE_SEGMENT = '[locale]';

export async function GET(req: NextRequest) {
const params = req.nextUrl.searchParams;
const token = params.get('token');
Expand All @@ -16,7 +18,7 @@ export async function GET(req: NextRequest) {

try {
if (!path) {
const localeSegment = getProjectLocales().length > 1 ? '/[locale]' : '';
const localeSegment = getProjectLocales().length > 1 ? `/${LOCALE_SEGMENT}` : '';
revalidatePath(`${localeSegment}/[[..contentPath]]/page`, 'page');
console.info(`Revalidated everything`);
} else {
Expand Down
2 changes: 1 addition & 1 deletion src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ export default function RootLayout({children}: LayoutProps) {
export function generateMetadata(): Metadata {
return {
title: {
default: 'Next.js + Enonic XP = Next.XP',
default: 'Next.XP 3.0',
template: '%s | Next.XP',
},
description: 'The React Framework for Enonic XP',
Expand Down
Loading

0 comments on commit 31eb6c3

Please sign in to comment.