Skip to content

Commit

Permalink
add to vercel site
Browse files Browse the repository at this point in the history
  • Loading branch information
paulpopus committed Dec 4, 2024
1 parent 539790d commit 3c45761
Show file tree
Hide file tree
Showing 16 changed files with 189 additions and 20 deletions.
9 changes: 4 additions & 5 deletions templates/with-vercel-website/.env.example
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
# Database connection string
POSTGRES_URL=postgresql://127.0.0.1:5432/payload-template-website
POSTGRES_URL=mongodb://127.0.0.1/payload-template-website
# Or use a PG connection string
#DATABASE_URI=postgresql://127.0.0.1:5432/payload-template-website
# Used to encrypt JWT tokens
PAYLOAD_SECRET=YOUR_SECRET_HERE
# Used to configure CORS, format links and more. No trailing slash
NEXT_PUBLIC_SERVER_URL=http://localhost:3000

# Your Vercel Blob storage write token
BLOB_READ_WRITE_TOKEN='vercel_blob_rw_test_123'
NEXT_PUBLIC_SERVER_URL=http://localhost:3000
3 changes: 3 additions & 0 deletions templates/with-vercel-website/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ node_modules

# Payload default media upload directory
public/media/

public/robots.txt
public/sitemap*.xml
3 changes: 2 additions & 1 deletion templates/with-vercel-website/.npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
legacy-peer-deps=true
legacy-peer-deps=true
enable-pre-post-scripts=true
14 changes: 14 additions & 0 deletions templates/with-vercel-website/next-sitemap.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/** @type {import('next-sitemap').IConfig} */
const SITE_URL =
process.env.NEXT_PUBLIC_SERVER_URL ||
process.env.VERCEL_PROJECT_PRODUCTION_URL ||
'https://example.com'

module.exports = {
siteUrl: SITE_URL,
generateRobotsTxt: true,
exclude: ['/posts-sitemap.xml', '/pages-sitemap.xml', '/*', '/posts/*'],
robotsTxtOptions: {
additionalSitemaps: [`${SITE_URL}/pages-sitemap.xml`, `${SITE_URL}/posts-sitemap.xml`],
},
}
4 changes: 3 additions & 1 deletion templates/with-vercel-website/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"type": "module",
"scripts": {
"build": "cross-env NODE_OPTIONS=--no-deprecation next build",
"postbuild": "next-sitemap --config next-sitemap.config.cjs",
"ci": "payload migrate && pnpm build",
"dev": "cross-env NODE_OPTIONS=--no-deprecation next dev",
"dev:prod": "cross-env NODE_OPTIONS=--no-deprecation rm -rf .next && pnpm build && pnpm start",
Expand Down Expand Up @@ -43,6 +44,7 @@
"jsonwebtoken": "9.0.2",
"lucide-react": "^0.378.0",
"next": "^15.0.3",
"next-sitemap": "^4.2.3",
"payload": "latest",
"payload-admin-bar": "^1.0.6",
"prism-react-renderer": "^2.3.1",
Expand All @@ -65,7 +67,7 @@
"autoprefixer": "^10.4.19",
"copyfiles": "^2.4.1",
"eslint": "^8",
"eslint-config-next": "15.0.3",
"eslint-config-next": "^15.0.3",
"postcss": "^8.4.38",
"prettier": "^3.0.3",
"tailwindcss": "^3.4.3",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const HeaderClient: React.FC<HeaderClientProps> = ({ header }) => {

return (
<header className="container relative z-20 " {...(theme ? { 'data-theme': theme } : {})}>
<div className="py-8 border-b border-border flex justify-between">
<div className="py-8 flex justify-between">
<Link href="/">
<Logo loading="eager" priority="high" className="invert dark:invert-0" />
</Link>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { getServerSideSitemap } from 'next-sitemap'
import { getPayload } from 'payload'
import config from '@payload-config'
import { unstable_cache } from 'next/cache'

const getPagesSitemap = unstable_cache(
async () => {
const payload = await getPayload({ config })
const SITE_URL =
process.env.NEXT_PUBLIC_SERVER_URL ||
process.env.VERCEL_PROJECT_PRODUCTION_URL ||
'https://example.com'

const results = await payload.find({
collection: 'pages',
overrideAccess: false,
draft: false,
depth: 0,
limit: 1000,
pagination: false,
where: {
_status: {
equals: 'published',
},
},
select: {
slug: true,
updatedAt: true,
},
})

const dateFallback = new Date().toISOString()

const defaultSitemap = [
{
loc: `${SITE_URL}/search`,
lastmod: dateFallback,
},
{
loc: `${SITE_URL}/posts`,
lastmod: dateFallback,
},
]

const sitemap = results.docs
? results.docs
.filter((page) => Boolean(page?.slug))
.map((page) => {
return {
loc: page?.slug === 'home' ? `${SITE_URL}/` : `${SITE_URL}/${page?.slug}`,
lastmod: page.updatedAt || dateFallback,
}
})
: []

return [...defaultSitemap, ...sitemap]
},
['pages-sitemap'],
{
tags: ['pages-sitemap'],
},
)

export async function GET() {
const sitemap = await getPagesSitemap()

return getServerSideSitemap(sitemap)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { getServerSideSitemap } from 'next-sitemap'
import { getPayload } from 'payload'
import config from '@payload-config'
import { unstable_cache } from 'next/cache'

const getPostsSitemap = unstable_cache(
async () => {
const payload = await getPayload({ config })
const SITE_URL =
process.env.NEXT_PUBLIC_SERVER_URL ||
process.env.VERCEL_PROJECT_PRODUCTION_URL ||
'https://example.com'

const results = await payload.find({
collection: 'posts',
overrideAccess: false,
draft: false,
depth: 0,
limit: 1000,
pagination: false,
where: {
_status: {
equals: 'published',
},
},
select: {
slug: true,
updatedAt: true,
},
})

const dateFallback = new Date().toISOString()

const sitemap = results.docs
? results.docs
.filter((post) => Boolean(post?.slug))
.map((post) => ({
loc: `${SITE_URL}/posts/${post?.slug}`,
lastmod: post.updatedAt || dateFallback,
}))
: []

return sitemap
},
['posts-sitemap'],
{
tags: ['posts-sitemap'],
},
)

export async function GET() {
const sitemap = await getPostsSitemap()

return getServerSideSitemap(sitemap)
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export async function generateStaticParams() {
draft: false,
limit: 1000,
overrideAccess: false,
pagination: false,
select: {
slug: true,
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,12 @@ export default async function Page({ searchParams: searchParamsPromise }: Args)
<div className="pt-24 pb-24">
<PageClient />
<div className="container mb-16">
<div className="prose dark:prose-invert max-w-none">
<h1 className="sr-only">Search</h1>
<Search />
<div className="prose dark:prose-invert max-w-none text-center">
<h1 className="mb-8 lg:mb-16">Search</h1>

<div className="max-w-[50rem] mx-auto">
<Search />
</div>
</div>
</div>

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { CollectionAfterChangeHook } from 'payload'
import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'

import { revalidatePath } from 'next/cache'
import { revalidatePath, revalidateTag } from 'next/cache'

import type { Page } from '../../../payload-types'

Expand All @@ -15,6 +15,7 @@ export const revalidatePage: CollectionAfterChangeHook<Page> = ({
payload.logger.info(`Revalidating page at path: ${path}`)

revalidatePath(path)
revalidateTag('pages-sitemap')
}

// If the page was previously published, we need to revalidate the old path
Expand All @@ -24,7 +25,16 @@ export const revalidatePage: CollectionAfterChangeHook<Page> = ({
payload.logger.info(`Revalidating old page at path: ${oldPath}`)

revalidatePath(oldPath)
revalidateTag('pages-sitemap')
}

return doc
}

export const revalidateDelete: CollectionAfterDeleteHook<Page> = ({ doc }) => {
const path = doc?.slug === 'home' ? '/' : `/${doc?.slug}`
revalidatePath(path)
revalidateTag('pages-sitemap')

return doc
}
5 changes: 3 additions & 2 deletions templates/with-vercel-website/src/collections/Pages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { hero } from '@/heros/config'
import { slugField } from '@/fields/slug'
import { populatePublishedAt } from '../../hooks/populatePublishedAt'
import { generatePreviewPath } from '../../utilities/generatePreviewPath'
import { revalidatePage } from './hooks/revalidatePage'
import { revalidateDelete, revalidatePage } from './hooks/revalidatePage'

import {
MetaDescriptionField,
Expand All @@ -32,7 +32,7 @@ export const Pages: CollectionConfig<'pages'> = {
},
// This config controls what's populated by default when a page is referenced
// https://payloadcms.com/docs/queries/select#defaultpopulate-collection-config-property
// Type safe if the collection slug generic is passed to `CollectionConfig` - `CollectionConfig<'pagess'>
// Type safe if the collection slug generic is passed to `CollectionConfig` - `CollectionConfig<'pages'>
defaultPopulate: {
title: true,
slug: true,
Expand Down Expand Up @@ -124,6 +124,7 @@ export const Pages: CollectionConfig<'pages'> = {
hooks: {
afterChange: [revalidatePage],
beforeChange: [populatePublishedAt],
beforeDelete: [revalidateDelete],
},
versions: {
drafts: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { CollectionAfterChangeHook } from 'payload'
import type { CollectionAfterChangeHook, CollectionAfterDeleteHook } from 'payload'

import { revalidatePath } from 'next/cache'
import { revalidatePath, revalidateTag } from 'next/cache'

import type { Post } from '../../../payload-types'

Expand All @@ -15,6 +15,7 @@ export const revalidatePost: CollectionAfterChangeHook<Post> = ({
payload.logger.info(`Revalidating post at path: ${path}`)

revalidatePath(path)
revalidateTag('posts-sitemap')
}

// If the post was previously published, we need to revalidate the old path
Expand All @@ -24,7 +25,17 @@ export const revalidatePost: CollectionAfterChangeHook<Post> = ({
payload.logger.info(`Revalidating old post at path: ${oldPath}`)

revalidatePath(oldPath)
revalidateTag('posts-sitemap')
}

return doc
}

export const revalidateDelete: CollectionAfterDeleteHook<Post> = ({ doc }) => {
const path = `/posts/${doc?.slug}`

revalidatePath(path)
revalidateTag('posts-sitemap')

return doc
}
3 changes: 2 additions & 1 deletion templates/with-vercel-website/src/collections/Posts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { Code } from '../../blocks/Code/config'
import { MediaBlock } from '../../blocks/MediaBlock/config'
import { generatePreviewPath } from '../../utilities/generatePreviewPath'
import { populateAuthors } from './hooks/populateAuthors'
import { revalidatePost } from './hooks/revalidatePost'
import { revalidateDelete, revalidatePost } from './hooks/revalidatePost'

import {
MetaDescriptionField,
Expand Down Expand Up @@ -219,6 +219,7 @@ export const Posts: CollectionConfig<'posts'> = {
hooks: {
afterChange: [revalidatePost],
afterRead: [populateAuthors],
afterDelete: [revalidateDelete],
},
versions: {
drafts: {
Expand Down
1 change: 0 additions & 1 deletion templates/with-vercel-website/src/fields/link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ export const link: LinkType = ({ appearances, disableLabel = false, overrides =
condition: (_, siblingData) => siblingData?.type === 'reference',
},
label: 'Document to link to',
maxDepth: 1,
relationTo: ['pages'],
required: true,
},
Expand Down
3 changes: 2 additions & 1 deletion templates/with-vercel-website/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"**/*.tsx",
".next/types/**/*.ts",
"redirects.js",
"next.config.js"
"next.config.js",
"next-sitemap.config.cjs"
],
"exclude": [
"node_modules"
Expand Down

0 comments on commit 3c45761

Please sign in to comment.