Skip to content

Commit

Permalink
fix(pdc-frontend): fix preview mode 404 & improve preview component
Browse files Browse the repository at this point in the history
  • Loading branch information
AliKdhim87 committed Oct 19, 2023
1 parent 8995edd commit 44e42bf
Show file tree
Hide file tree
Showing 7 changed files with 44 additions and 34 deletions.
2 changes: 1 addition & 1 deletion apps/pdc-frontend/src/app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ const RootLayout = async ({ children, params: { locale } }: LayoutProps) => {
closeText: 'Sluiten',
}}
/>
<PageContent className="utrecht-page-content--modifier" style={{ position: 'relative' }}>
<PageContent className="utrecht-page-content--modifier">
<Main id="main">{children}</Main>
</PageContent>
<Footer data={footerData} />
Expand Down
31 changes: 12 additions & 19 deletions apps/pdc-frontend/src/app/[locale]/products/[slug]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import isAbsoluteUrl from 'is-absolute-url';
import { Metadata } from 'next';
import { cookies, draftMode } from 'next/headers';
import { draftMode } from 'next/headers';
import Image from 'next/image';
import { notFound } from 'next/navigation';
import React from 'react';
Expand Down Expand Up @@ -42,9 +42,7 @@ const getAllProducts = async (locale: string, slug: string) => {
},
});

if (!data || data?.products?.data?.length === 0) {
notFound();
}
if (!data || data?.products?.data?.length === 0) notFound();

return {
product: data?.products?.data[0],
Expand Down Expand Up @@ -72,13 +70,8 @@ export async function generateMetadata({ params }: any): Promise<Metadata> {
};
}

const Product = async ({ params: { locale, slug }, searchParams }: ProductProps) => {
const currentToken = cookies().has('secret') && cookies().get('secret')?.value;
const isCurrentPreviewTokenValid = searchParams.secret === currentToken;
const Product = async ({ params: { locale, slug } }: ProductProps) => {
const { isEnabled } = draftMode();
if (!isCurrentPreviewTokenValid) {
draftMode().disable();
}
const { product } = await getAllProducts(locale, slug);

const priceData = product?.attributes.price && product?.attributes.price?.data?.attributes.price;
Expand Down Expand Up @@ -190,6 +183,15 @@ const Product = async ({ params: { locale, slug }, searchParams }: ProductProps)
: null;
return (
<>
{isEnabled && (
<PreviewAlert
link={{
href: `/api/clear-preview?slug=${locale}${slug}&default_locale=${fallbackLng}`,
text: t('preview-alert.link'),
}}
message={t('preview-alert.message')}
/>
)}
<Breadcrumbs
links={[
{
Expand All @@ -210,15 +212,6 @@ const Product = async ({ params: { locale, slug }, searchParams }: ProductProps)
]}
/>
<Article>
{isCurrentPreviewTokenValid && isEnabled && (
<PreviewAlert
link={{
href: `/api/clear-preview?slug=${locale}${slug}&default_locale=${fallbackLng}`,
text: t('preview-alert.button'),
}}
message={t('preview-alert.message')}
/>
)}
<PageTitle>{product?.attributes.title}</PageTitle>
{product?.attributes?.content && (
<Markdown imageUrl={getImageBaseUrl()} priceData={priceData} locale={locale}>
Expand Down
11 changes: 5 additions & 6 deletions apps/pdc-frontend/src/app/api/preview/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { RedirectType } from 'next/dist/client/components/redirect';
import { cookies, draftMode } from 'next/headers';
import { draftMode } from 'next/headers';
import { redirect } from 'next/navigation';
import { GET_PRODUCT_BY_SLUG_AND_LOCALE_FETCH } from '@/query';
import { createStrapiURL } from '@/util/createStrapiURL';
Expand All @@ -17,6 +16,8 @@ export async function GET(request: Request) {
// This secret should only be known to this route handler and the CMS
if (secret !== process.env.PREVIEW_SECRET_TOKEN) {
return new Response('Invalid token', { status: 401 });
} else if (!slug || !type) {
return new Response('Missing required parameters', { status: 422 });
}

// Fetch the headless CMS to check if the provided `slug` exists
Expand All @@ -35,12 +36,10 @@ export async function GET(request: Request) {
return new Response('Invalid slug', { status: 401 });
}

const path = `/${locale}/${type}/${data.products?.data[0]?.attributes.slug}?secret=${process.env.PREVIEW_SECRET_TOKEN}`;
const path = `/${locale}/${type}/${data.products?.data[0]?.attributes.slug}`;
// Enable Draft Mode by setting the cookie
cookies().set('secret', secret);

draftMode().enable();
// Redirect to the path from the fetched post
// We don't redirect to searchParams.slug as that might lead to open redirect vulnerabilities
redirect(path, RedirectType.replace);
redirect(path);
}
4 changes: 2 additions & 2 deletions apps/pdc-frontend/src/app/i18n/locales/en/common.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"preview-alert": {
"message": "Warning: Preview mode is on",
"button": "Turn off the preview mode"
"message": "Preview Mode: Enabled",
"link": "(You can disable it in settings)"
},
"actions": {
"try-again": "Try again",
Expand Down
4 changes: 2 additions & 2 deletions apps/pdc-frontend/src/app/i18n/locales/nl/common.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"preview-alert": {
"message": "Waarschuwing: voorbeeldmodus is ingeschakeld",
"button": "Schakel de voorbeeldmodus uit"
"message": "Testmodus: Ingeschakeld ",
"link": "(U kunt deze uitschakelen in de instellingen)"
},
"actions": {
"try-again": "Probeer opnieuw",
Expand Down
13 changes: 13 additions & 0 deletions apps/pdc-frontend/src/components/PreviewAlert/index.module.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
.utrecht-preview-mode {
// TODO: move this component to ui package
--utrecht-space-around: 0;
--utrecht-alert-padding-block-start: 10px;
--utrecht-alert-padding-block-end: 10px;

inline-size: 100%;
left: 0;
position: absolute;
text-align: center;
top: 0;
z-index: 100;
}
13 changes: 9 additions & 4 deletions apps/pdc-frontend/src/components/PreviewAlert/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import classnames from 'classnames/bind';
import React from 'react';
import { Alert, ButtonLink, Paragraph } from '@/components';
import { Alert, Link, Paragraph } from '@/components';
import styles from './index.module.scss';

const css = classnames.bind(styles);

type LinkTypes = {
href: string;
Expand All @@ -12,8 +16,9 @@ interface PreviewAlertProps {
}

export const PreviewAlert = ({ link, message }: PreviewAlertProps) => (
<Alert type="warning">
<ButtonLink href={link.href}>{link.text}</ButtonLink>
<Paragraph>{message}</Paragraph>
<Alert type="warning" className={css('utrecht-preview-mode')}>
<Paragraph>
{message} <Link href={link.href}>{link.text}</Link>
</Paragraph>
</Alert>
);

0 comments on commit 44e42bf

Please sign in to comment.