prefix
stringlengths
512
512
suffix
stringlengths
256
256
middle
stringlengths
14
229
meta
dict
import { getDraftPost } from "@/lib/api"; import { BUILDER_CONFIG } from "@/lib/constants"; import querystring from "querystring"; export default async function preview(req, res) { const postId = req.query[`builder.overrides.${BUILDER_CONFIG.postsModel}`]; if (req.query.secret !== BUILDER_CONFIG.previewSecret || !...
Id, }); // Redirect to the path from the fetched post // We don't redirect to req.query.slug as that might lead to open redirect vulnerabilities res.writeHead(307, { Location: `/posts/${post.data.slug}?${querystring.stringify(req.query)}`, }
doesn't exist prevent preview mode from being enabled if (!post) { return res.status(401).json({ message: "Invalid post" }); } // Enable Preview Mode by setting the cookies res.setPreviewData({ postDraftId: post
{ "filepath": "examples/cms-builder-io/pages/api/preview.js", "language": "javascript", "file_size": 1015, "cut_index": 512, "middle_length": 229 }
t } from "@vercel/blob"; import sharp from "sharp"; import type { ImageProps } from "./types"; let cached: ImageProps[] | null = null; async function fetchBuffer(url: string): Promise<Buffer> { const res = await fetch(url); if (!res.ok) throw new Error(`${res.status} fetching ${url}`); return Buffer.from(await ...
jpeg;base64,${placeholder.toString("base64")}`, }; } export default async function getResults(): Promise<ImageProps[]> { if (cached) return cached; const { blobs } = await list(); // Newest-first ordering by pathname (mirrors the original Cloudin
= await sharp(buf).metadata(); const placeholder = await sharp(buf) .resize(10) .jpeg({ quality: 70 }) .toBuffer(); return { width: meta.width ?? 0, height: meta.height ?? 0, blurDataUrl: `data:image/
{ "filepath": "examples/with-vercel-blob/utils/cachedImages.ts", "language": "typescript", "file_size": 1364, "cut_index": 524, "middle_length": 229 }
s"; import { Author as ViewModelAuthor } from "@/viewmodels/author"; import { Post as ViewModelPost } from "@/viewmodels/post"; import { DeliveryClient } from "@kontent-ai/delivery-sdk"; import pkg from "../package.json"; const sourceTrackingHeaderName = "X-KC-SOURCE"; const client = new DeliveryClient({ projectId:...
} function parsePost(post: Post): ViewModelPost { return { title: post.elements.title.value, slug: post.elements.slug.value, date: post.elements.date.value, content: post.elements.content.value, excerpt: post.elements.excerpt.value,
ercel/next.js/example/${pkg.name};${pkg.version}`, }, ], }); function parseAuthor(author: Author): ViewModelAuthor { return { name: author.elements.name.value, picture: author.elements.picture.value[0].url, };
{ "filepath": "examples/cms-kontent-ai/lib/api.ts", "language": "typescript", "file_size": 2513, "cut_index": 563, "middle_length": 229 }
ronment: Production * Project Id: a7844231-064c-016c-1dad-38228cbc505d */ export const contentTypes = { /** * Author */ author: { codename: "author", id: "c204b17f-d320-5755-b913-7b4caa8902b6", externalId: "ba75f751-d649-4fad-a643-bd58c660bb86", name: "Author", elements: { /** ...
-de37d3aa263b", externalId: "7a94a17f-fbe6-4415-a0fd-a99d150d74e3", name: "Picture", required: false, type: "asset", snippetCodename: undefined, }, }, }, /** * Post */ post: { codename: "po
"Name", required: false, type: "text", snippetCodename: undefined, }, /** * Picture (asset) */ picture: { codename: "picture", id: "78b67780-55e4-5b29-903c
{ "filepath": "examples/cms-kontent-ai/models/project/contentTypes.ts", "language": "typescript", "file_size": 3536, "cut_index": 614, "middle_length": 229 }
e IContentItem, type Elements } from "@kontent-ai/delivery-sdk"; import { type Author } from "./author"; /** * Generated by '@kontent-ai/model-generator@5.9.0' * * Post * Id: b1efdda5-18a3-5445-8ca2-51c252a9ee2d * Codename: post */ export type Post = IContentItem<{ /** * Author (modular_content) * Requir...
*/ cover_image: Elements.AssetsElement; /** * Date (date_time) * Required: false * Id: 1739ed56-ccd8-55a3-9cd3-67f09a8073db * Codename: date */ date: Elements.DateTimeElement; /** * Excerpt (text) * Required: false * I
f8b91d9f-0a7d-557e-9fe8-ca1203ae4a67 * Codename: content */ content: Elements.RichTextElement; /** * Cover Image (asset) * Required: false * Id: 8f1bd2ae-b15a-5100-b8ee-b279a87862fb * Codename: cover_image
{ "filepath": "examples/cms-kontent-ai/models/content-types/post.ts", "language": "typescript", "file_size": 1418, "cut_index": 524, "middle_length": 229 }
Container from "./container"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-...
er border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/
flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black bord
{ "filepath": "examples/cms-kontent-ai/components/footer.tsx", "language": "tsx", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
kontent-ai/delivery-sdk"; const srcIsKontentAsset = (src: string) => { try { const { hostname } = new URL(src); return hostname.endsWith(".kc-usercontent.com"); } catch { return false; } }; const kontentImageLoader = ({ src, width, quality = 75, }: ImageLoaderProps): string => { return trans...
ed; }; type ImageType = { width?: number; height?: number; src: string; layout?: string; className: string; alt: string; }; export default function Image(props: ImageType) { const loader = getLoader(props.src); return <NextImage {...prop
rcIsKontentAsset(src) ? kontentImageLoader : undefin
{ "filepath": "examples/cms-kontent-ai/components/image.tsx", "language": "tsx", "file_size": 939, "cut_index": 606, "middle_length": 52 }
from "next/head"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants"; export default function Meta() { return ( <Head> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" ...
/favicon.ico" /> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-config" content="/favicon/browserconfig.xml" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="application/
/> <link rel="manifest" href="/favicon/site.webmanifest" /> <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#000000" /> <link rel="shortcut icon" href="/favicon
{ "filepath": "examples/cms-kontent-ai/components/meta.tsx", "language": "tsx", "file_size": 1255, "cut_index": 524, "middle_length": 229 }
tter from "./date-formatter"; import CoverImage from "./cover-image"; import Link from "next/link"; import { Post } from "@/viewmodels/post"; type PostPreviewProps = { post: Post; }; export default function PostPreview({ post }: PostPreviewProps) { return ( <div> <div className="mb-5"> <CoverIma...
</h3> <div className="text-lg mb-4"> <DateFormatter dateString={post.date} /> </div> <p className="text-lg leading-relaxed mb-4">{post.excerpt}</p> <Avatar name={post.author.name} picture={post.author.picture} /> </div>
line"> {post.title} </Link>
{ "filepath": "examples/cms-kontent-ai/components/post-preview.tsx", "language": "tsx", "file_size": 874, "cut_index": 559, "middle_length": 52 }
ort { NextApiRequest, NextApiResponse } from "next"; import { getPostBySlug } from "../../lib/api"; export default async function preview( req: NextApiRequest, res: NextApiResponse, ) { // Check the secret and next parameters // This secret should only be known to this API route and the CMS if ( req.quer...
tus(401).json({ message: "Invalid slug" }); } // Enable Preview Mode by setting the cookie res.setDraftMode({ enable: true }); // Redirect to the path from the fetched post // We don't redirect to req.query.slug as that might lead to open redir
the headless CMS to check if the provided `slug` exists const post = await getPostBySlug(req.query.slug as string, true); // If the slug doesn't exist prevent preview mode from being enabled if (!post) { return res.sta
{ "filepath": "examples/cms-kontent-ai/pages/api/preview.ts", "language": "typescript", "file_size": 1094, "cut_index": 515, "middle_length": 229 }
; const ViewSource = ({ pathname }: ViewSourceProps) => ( <svg xmlns="http://www.w3.org/2000/svg" width="80" height="80" viewBox="0 0 250 250" fill="#151513" className={styles.svg} > <a title="View Source" href={`https://github.com/vercel/next.js/blob/canary/examples/image-c...
path d="M115 115s4 2 5 0l14-14c3-2 6-3 8-3-8-11-15-24 2-41 5-5 10-7 16-7 1-2 3-7 12-11 0 0 5 3 7 16 4 2 8 5 12 9s7 8 9 12c14 3 17 7 17 7-4 8-9 11-11 11 0 6-2 11-7 16-16 16-30 10-41 2 0 3-1 7-5 11l-12 11c-1 1 1 5 1 5z" /> </a> </svg> ); export defaul
2 3-2 4 5 2 11 2 11-3 10 5 15 9 16" /> <
{ "filepath": "examples/image-component/components/view-source.tsx", "language": "tsx", "file_size": 928, "cut_index": 606, "middle_length": 52 }
ort Document, { Head, Html, Main, NextScript } from "next/document"; class MyDocument extends Document { render() { return ( <Html lang="en"> <Head> <link rel="icon" href="/favicon.ico" /> <meta name="description" content="See pictures from Next.js Conf a...
"twitter:title" content="Next.js Conf 2022 Pictures" /> <meta name="twitter:description" content="See pictures from Next.js Conf and the After Party." /> </Head> <body className="bg-black antialia
pictures from Next.js Conf and the After Party." /> <meta property="og:title" content="Next.js Conf 2022 Pictures" /> <meta name="twitter:card" content="summary_large_image" /> <meta name=
{ "filepath": "examples/with-vercel-blob/pages/_document.tsx", "language": "tsx", "file_size": 1121, "cut_index": 515, "middle_length": 229 }
* @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: { colors: { "accent-1": "#FAFAFA", "accent-2": "#EAEAEA", "accent-7": "#333", success: "#0070f3", ...
"5xl": "2.5rem", "6xl": "2.75rem", "7xl": "4.5rem", "8xl": "6.25rem", }, boxShadow: { small: "0 5px 10px rgba(0, 0, 0, 0.12)", medium: "0 8px 30px rgba(0, 0, 0, 0.12)", }, }, }, plugins:
tSize: {
{ "filepath": "examples/cms-kontent-ai/tailwind.config.js", "language": "javascript", "file_size": 791, "cut_index": 514, "middle_length": 14 }
iner from "./container"; import cn from "classnames"; import { EXAMPLE_PATH } from "../lib/constants"; type AlertProps = { preview: boolean }; export default function Alert({ preview }: AlertProps) { return ( <div className={cn("border-b", { "bg-accent-7 border-accent-7 text-white": preview, ...
to exit preview mode. </> ) : ( <> The source code for this blog is{" "} <a href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`}
s a preview.{" "} <a href="/api/exit-preview" className="underline hover:text-cyan duration-200 transition-colors" > Click here </a>{" "}
{ "filepath": "examples/cms-kontent-ai/components/alert.tsx", "language": "tsx", "file_size": 1256, "cut_index": 524, "middle_length": 229 }
URL } from "../lib/constants"; export default function Intro() { return ( <section className="flex-col md:flex-row flex items-center md:justify-between mt-16 mb-16 md:mb-12"> <h1 className="text-6xl md:text-8xl font-bold tracking-tighter leading-tight md:pr-8"> Blog. </h1> <h4 className...
Next.js </a>{" "} and{" "} <a href={CMS_URL} className="underline hover:text-success duration-200 transition-colors" > {CMS_NAME} </a> . </h4> </section> )
xt-success duration-200 transition-colors" >
{ "filepath": "examples/cms-kontent-ai/components/intro.tsx", "language": "tsx", "file_size": 847, "cut_index": 535, "middle_length": 52 }
iner from "../components/container"; import MoreStories from "../components/more-stories"; import HeroPost from "../components/hero-post"; import Intro from "../components/intro"; import Layout from "../components/layout"; import { getAllPosts } from "../lib/api"; import Head from "next/head"; import { CMS_NAME } from ...
<Container> <Intro /> {heroPost && ( <HeroPost title={heroPost.title} coverImage={heroPost.coverImage} date={heroPost.date} author={heroPost.author}
ops) { const heroPost = allPosts[0]; const morePosts = allPosts.slice(1); return ( <> <Layout preview={preview}> <Head> <title>{`Next.js Blog Example with ${CMS_NAME}`}</title> </Head>
{ "filepath": "examples/cms-kontent-ai/pages/index.tsx", "language": "tsx", "file_size": 1387, "cut_index": 524, "middle_length": 229 }
{ GetStaticProps, NextPage } from "next"; import Head from "next/head"; import { useRouter } from "next/router"; import Carousel from "../../components/Carousel"; import getResults from "../../utils/cachedImages"; import type { ImageProps } from "../../utils/types"; const Home: NextPage = ({ currentPhoto }: { currentP...
tPhoto={currentPhoto} index={index} /> </main> </> ); }; export default Home; export const getStaticProps: GetStaticProps = async (context) => { const images = await getResults(); const currentPhoto = images.find( (img) => img.id ===
s</title> <meta property="og:image" content={currentPhoto.url} /> <meta name="twitter:image" content={currentPhoto.url} /> </Head> <main className="mx-auto max-w-[1960px] p-4"> <Carousel curren
{ "filepath": "examples/with-vercel-blob/pages/p/[photoId].tsx", "language": "tsx", "file_size": 1287, "cut_index": 524, "middle_length": 229 }
Avatar from "../components/avatar"; import DateFormatter from "../components/date-formatter"; import CoverImage from "../components/cover-image"; import Link from "next/link"; type HeroPostProps = { title: string; coverImage: string; date: string | null; excerpt: string; author: { name: string; pict...
-4 text-4xl lg:text-6xl leading-tight"> <Link href={`/posts/${slug}`} className="hover:underline"> {title} </Link> </h3> <div className="mb-4 md:mb-0 text-lg"> <DateFormatter dateString=
ssName="mb-8 md:mb-16"> <CoverImage title={title} src={coverImage} slug={slug} /> </div> <div className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28"> <div> <h3 className="mb
{ "filepath": "examples/cms-kontent-ai/components/hero-post.tsx", "language": "tsx", "file_size": 1242, "cut_index": 518, "middle_length": 229 }
orPage from "next/error"; import Container from "../../components/container"; import PostBody from "../../components/post-body"; import MoreStories from "../../components/more-stories"; import Header from "../../components/header"; import PostHeader from "../../components/post-header"; import SectionSeparator from "../...
odel>; preview: boolean; }; export default function Post({ post, morePosts = [], preview }: PostProps) { const router = useRouter(); if (!router.isFallback && !post?.slug) { return <ErrorPage statusCode={404} />; } return ( <Layout previ
m "../../components/post-title"; import Head from "next/head"; import { CMS_NAME } from "../../lib/constants"; import { Post as PostModel } from "@/viewmodels/post"; type PostProps = { post: PostModel; morePosts: Array<PostM
{ "filepath": "examples/cms-kontent-ai/pages/posts/[slug].tsx", "language": "tsx", "file_size": 2595, "cut_index": 563, "middle_length": 229 }
import Avatar from "./avatar"; import DateFormatter from "./date-formatter"; import CoverImage from "./cover-image"; import PostTitle from "./post-title"; import { Author } from "@/viewmodels/author"; type PostHeaderType = { title: string; coverImage: string; date: string | null; author: Author; }; export def...
uto"> <div className="block md:hidden mb-6"> <Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-6 text-lg"> <DateFormatter dateString={date} /> </div> </div> </>
<Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-8 md:mb-16 -mx-5 sm:mx-0"> <CoverImage title={title} src={coverImage} /> </div> <div className="max-w-2xl mx-a
{ "filepath": "examples/cms-kontent-ai/components/post-header.tsx", "language": "tsx", "file_size": 1002, "cut_index": 512, "middle_length": 229 }
irect } from "next/navigation"; import { createClient } from "@/lib/supabase/server"; import { InfoIcon } from "lucide-react"; import { FetchDataSteps } from "@/components/tutorial/fetch-data-steps"; import { Suspense } from "react"; async function UserDetails() { const supabase = await createClient(); const { da...
nfoIcon size="16" strokeWidth={2} /> This is a protected page that you can only see as an authenticated user </div> </div> <div className="flex flex-col gap-2 items-start"> <h2 className="font-bold text-2xl m
ectedPage() { return ( <div className="flex-1 w-full flex flex-col gap-12"> <div className="w-full"> <div className="bg-accent text-sm p-3 px-5 rounded-md text-foreground flex gap-3 items-center"> <I
{ "filepath": "examples/with-supabase/app/protected/page.tsx", "language": "tsx", "file_size": 1356, "cut_index": 524, "middle_length": 229 }
ort Image, { ImageProps } from "next/image"; import ViewSource from "../../components/view-source"; import styles from "../../styles.module.css"; // Note: we cannot use `priority` or `loading="eager" // because we depend on the default `loading="lazy"` // behavior to wait for CSS to reveal the proper image. type Props...
e/page.tsx" /> <h1>Image With Light/Dark Theme Detection</h1> <ThemeImage alt="Next.js Streaming" srcLight="https://assets.vercel.com/image/upload/front/nextjs/streaming-light.png" srcDark="https://assets.vercel.com/image/upload/f
urn ( <> <Image {...rest} src={srcLight} className={styles.imgLight} /> <Image {...rest} src={srcDark} className={styles.imgDark} /> </> ); }; const Page = () => ( <div> <ViewSource pathname="app/them
{ "filepath": "examples/image-component/app/theme/page.tsx", "language": "tsx", "file_size": 1110, "cut_index": 515, "middle_length": 229 }
Image from "next/image"; import ViewSource from "../../components/view-source"; const shimmer = (w: number, h: number) => ` <svg width="${w}" height="${h}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <defs> <linearGradient id="g"> <stop stop-color="#333" of...
defined" ? Buffer.from(str).toString("base64") : window.btoa(str); const Shimmer = () => ( <div> <ViewSource pathname="app/shimmer/page.tsx" /> <h1>Image Component With Shimmer Data URL</h1> <Image alt="Mountains" src="/m
ect id="r" width="${w}" height="${h}" fill="url(#g)" /> <animate xlink:href="#r" attributeName="x" from="-${w}" to="${w}" dur="1s" repeatCount="indefinite" /> </svg>`; const toBase64 = (str: string) => typeof window === "un
{ "filepath": "examples/image-component/app/shimmer/page.tsx", "language": "tsx", "file_size": 1251, "cut_index": 518, "middle_length": 229 }
ort Image from "next/image"; import ViewSource from "../../components/view-source"; import mountains from "../../public/mountains.jpg"; const Fill = () => ( <div> <ViewSource pathname="app/fill/page.tsx" /> <h1>Image Component With Layout Fill</h1> <div style={{ position: "relative", width: "300px", heig...
/> </div> <div style={{ position: "relative", width: "300px", height: "500px" }}> <Image alt="Mountains" src={mountains} quality={100} fill sizes="100vw" style={{ objectFit: "no
<div style={{ position: "relative", width: "300px", height: "500px" }}> <Image alt="Mountains" src={mountains} fill sizes="100vw" style={{ objectFit: "contain", }}
{ "filepath": "examples/image-component/app/fill/page.tsx", "language": "tsx", "file_size": 1070, "cut_index": 515, "middle_length": 229 }
Container from "./container"; import cn from "classnames"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Alert({ preview }) { return ( <div className={cn("border-b", { "bg-accent-7 border-accent-7 text-white": preview, "bg-accent-1 border-accent-2": !preview, ...
</> ) : ( <> The source code for this blog is{" "} <a href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH}`} className="underline hover:text-success
href="/api/exit-preview" className="underline hover:text-cyan duration-200 transition-colors" > Click here </a>{" "} to exit preview mode.
{ "filepath": "examples/cms-tina/components/alert.js", "language": "javascript", "file_size": 1203, "cut_index": 518, "middle_length": 229 }
Avatar from "../components/avatar"; import DateFormatter from "../components/date-formatter"; import CoverImage from "../components/cover-image"; import Link from "next/link"; export default function HeroPost({ title, coverImage, date, excerpt, author, slug, }) { return ( <section> <div classN...
{title} </Link> </h3> <div className="mb-4 md:mb-0 text-lg"> <DateFormatter dateString={date} /> </div> </div> <div> <p className="text-lg leading-relaxed mb-4">{
iv className="md:grid md:grid-cols-2 md:gap-x-16 lg:gap-x-8 mb-20 md:mb-28"> <div> <h3 className="mb-4 text-4xl lg:text-6xl leading-tight"> <Link href={`/posts/${slug}`} className="hover:underline">
{ "filepath": "examples/cms-tina/components/hero-post.js", "language": "javascript", "file_size": 1131, "cut_index": 518, "middle_length": 229 }
vatar"; import DateFormatter from "../components/date-formatter"; import CoverImage from "../components/cover-image"; import PostTitle from "../components/post-title"; export default function PostHeader({ title, coverImage, date, author }) { return ( <> <PostTitle>{title}</PostTitle> <div className="...
<div className="max-w-2xl mx-auto"> <div className="block md:hidden mb-6"> <Avatar name={author.name} picture={author.picture} /> </div> <div className="mb-6 text-lg"> <DateFormatter dateString={date} />
rImage} height={620} width={1240} /> </div>
{ "filepath": "examples/cms-tina/components/post-header.js", "language": "javascript", "file_size": 894, "cut_index": 547, "middle_length": 52 }
iner from "../components/container"; import MoreStories from "../components/more-stories"; import HeroPost from "../components/hero-post"; import Intro from "../components/intro"; import Layout from "../components/layout"; import { getAllPosts } from "../lib/api"; import Head from "next/head"; import { CMS_NAME } from ...
roPost.coverImage} date={heroPost.date} author={heroPost.author} slug={heroPost.slug} excerpt={heroPost.excerpt} /> )} {morePosts.length > 0 && <MoreStories posts={more
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title> </Head> <Container> <Intro /> {heroPost && ( <HeroPost title={heroPost.title} coverImage={he
{ "filepath": "examples/cms-tina/pages/index.js", "language": "javascript", "file_size": 1281, "cut_index": 524, "middle_length": 229 }
"; const schema = defineSchema({ collections: [ { label: "Blog Posts", name: "posts", path: "_posts", fields: [ { type: "string", label: "Title", name: "title", }, { type: "string", label: "Excerpt", name:...
name: "name", }, { type: "string", label: "Picture", name: "picture", }, ], }, { type: "object", label: "OG Image", nam
name: "date", }, { type: "object", label: "author", name: "author", fields: [ { type: "string", label: "Name",
{ "filepath": "examples/cms-tina/.tina/schema.ts", "language": "typescript", "file_size": 2503, "cut_index": 563, "middle_length": 229 }
rom "next/server"; export function middleware(request) { const nonce = Buffer.from(crypto.randomUUID()).toString("base64"); const cspHeader = ` default-src 'self'; script-src 'self' 'nonce-${nonce}' 'strict-dynamic' https: http: ${ process.env.NODE_ENV === "production" ? "" : `'unsafe-eval'` }; ...
estHeaders.set("x-nonce", nonce); requestHeaders.set( "Content-Security-Policy", contentSecurityPolicyHeaderValue, ); const response = NextResponse.next({ request: { headers: requestHeaders, }, }); response.headers.set(
pgrade-insecure-requests; `; // Replace newline characters and spaces const contentSecurityPolicyHeaderValue = cspHeader .replace(/\s{2,}/g, " ") .trim(); const requestHeaders = new Headers(request.headers); requ
{ "filepath": "examples/with-strict-csp/middleware.js", "language": "javascript", "file_size": 1615, "cut_index": 537, "middle_length": 229 }
tyle({ WebkitFontSmoothing: "antialiased", WebkitTapHighlightColor: "transparent", alignItems: "center", background: "#FFF", borderRadius: "5px", border: "1px solid #FFF", boxSizing: "border-box", colorScheme: "dark", color: "#000", cursor: "pointer", display: "flex", fontSize: "0.875rem", fon...
one", textSizeAdjust: "100%", transitionDuration: ".15s", transitionProperty: "border-color, background, color, box-shadow", transitionTimingFunction: "ease", userSelect: "none", verticalAlign: "baseline", ":hover": { boxShadow: "none",
12px", position: "relative", textDecoration: "n
{ "filepath": "examples/with-vanilla-extract/components/Button.css.ts", "language": "typescript", "file_size": 978, "cut_index": 582, "middle_length": 52 }
om "tailwindcss"; export default { darkMode: ["class"], content: [ "./pages/**/*.{js,ts,jsx,tsx,mdx}", "./components/**/*.{js,ts,jsx,tsx,mdx}", "./app/**/*.{js,ts,jsx,tsx,mdx}", "./src/**/*.{js,ts,jsx,tsx,mdx}", ], theme: { extend: { colors: { background: "hsl(var(--background...
}, secondary: { DEFAULT: "hsl(var(--secondary))", foreground: "hsl(var(--secondary-foreground))", }, muted: { DEFAULT: "hsl(var(--muted))", foreground: "hsl(var(--muted-foreground))",
DEFAULT: "hsl(var(--popover))", foreground: "hsl(var(--popover-foreground))", }, primary: { DEFAULT: "hsl(var(--primary))", foreground: "hsl(var(--primary-foreground))",
{ "filepath": "examples/with-supabase/tailwind.config.ts", "language": "typescript", "file_size": 1846, "cut_index": 537, "middle_length": 229 }
"; import ViewSource from "../components/view-source"; import vercel from "../public/vercel.png"; import type { PropsWithChildren } from "react"; const Code = (props: PropsWithChildren<{}>) => ( <code className={styles.inlineCode} {...props} /> ); const Index = () => ( <div className={styles.container}> <View...
ocs/basic-features/image-optimization"> automatically optimize </a>{" "} images on-demand as the browser requests them. </p> <hr className={styles.hr} /> <h2 id="examples">Examples</h2> <p> Try it t
https://nextjs.org/docs/api-reference/next/image"> next/image </a>{" "} component with live examples. </p> <p> This component is designed to{" "} <a href="https://nextjs.org/d
{ "filepath": "examples/image-component/app/page.tsx", "language": "tsx", "file_size": 3489, "cut_index": 614, "middle_length": 229 }
from "next/image"; import ViewSource from "../../components/view-source"; // Pixel GIF code adapted from https://stackoverflow.com/a/33919020/266535 const keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; const triplet = (e1: number, e2: number, e3: number) => keyStr.charAt(e1 >> 2) +...
or Data URL</h1> <Image alt="Dog" src="/dog.jpg" placeholder="blur" blurDataURL={rgbDataURL(237, 181, 6)} width={750} height={1000} style={{ maxWidth: "100%", height: "auto", }} />
/gif;base64,R0lGODlhAQABAPAA${ triplet(0, r, g) + triplet(b, 255, 255) }/yH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==`; const Color = () => ( <div> <ViewSource pathname="app/color/page.tsx" /> <h1>Image Component With Col
{ "filepath": "examples/image-component/app/color/page.tsx", "language": "tsx", "file_size": 1277, "cut_index": 524, "middle_length": 229 }
ort fs from "fs"; import { join } from "path"; import matter from "gray-matter"; const postsDirectory = join(process.cwd(), "_posts"); export function getPostSlugs() { return fs.readdirSync(postsDirectory); } export function getPostBySlug(slug, fields = []) { const realSlug = slug.replace(/\.md$/, ""); const f...
!== "undefined") { items[field] = data[field]; } }); return items; } export function getAllPosts(fields = []) { const slugs = getPostSlugs(); const posts = slugs .map((slug) => getPostBySlug(slug, fields)) // sort posts by date
only the minimal needed data is exposed fields.forEach((field) => { if (field === "slug") { items[field] = realSlug; } if (field === "content") { items[field] = content; } if (typeof data[field]
{ "filepath": "examples/cms-tina/lib/api.js", "language": "javascript", "file_size": 1104, "cut_index": 515, "middle_length": 229 }
vatar"; import DateFormatter from "../components/date-formatter"; import CoverImage from "./cover-image"; import Link from "next/link"; export default function PostPreview({ title, coverImage, date, excerpt, author, slug, }) { return ( <div> <div className="mb-5"> <CoverImage ...
ne"> {title} </Link> </h3> <div className="text-lg mb-4"> <DateFormatter dateString={date} /> </div> <p className="text-lg leading-relaxed mb-4">{excerpt}</p> <Avatar name={author.name} picture={autho
ink href={`/posts/${slug}`} className="hover:underli
{ "filepath": "examples/cms-tina/components/post-preview.js", "language": "javascript", "file_size": 887, "cut_index": 547, "middle_length": 52 }
keyof T]: T[K] } export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> } export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: stri...
alars['String'] collection: Collection } export type SystemInfoBreadcrumbsArgs = { excludeExtension?: InputMaybe<Scalars['Boolean']> } export type PageInfo = { __typename?: 'PageInfo' hasPreviousPage: Scalars['Boolean'] hasNextPage: Scalars['Bo
typename?: 'SystemInfo' filename: Scalars['String'] basename: Scalars['String'] breadcrumbs: Array<Scalars['String']> path: Scalars['String'] relativePath: Scalars['String'] extension: Scalars['String'] template: Sc
{ "filepath": "examples/cms-tina/.tina/__generated__/types.ts", "language": "typescript", "file_size": 11000, "cut_index": 921, "middle_length": 229 }
0%", }); globalStyle("*, *::before, *::after", { boxSizing: "border-box", WebkitFontSmoothing: "antialiased", MozOsxFontSmoothing: "grayscale", }); globalStyle("body", { display: "flex", flexDirection: "column", margin: "0", fontFamily: "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,...
h2, h3, h4, p", { margin: 0, }); globalStyle("main", { display: "flex", alignItems: "center", justifyContent: "center", flexDirection: "column", position: "relative", width: "100%", height: "100%", maxWidth: "720px", margin: "0 auto",
backgroundRepeat: "no-repeat", }); globalStyle("h1,
{ "filepath": "examples/with-vanilla-extract/app/globalStyle.css.ts", "language": "typescript", "file_size": 941, "cut_index": 606, "middle_length": 52 }
Container from "./container"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-...
er border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/
flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black bord
{ "filepath": "examples/cms-tina/components/footer.js", "language": "javascript", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
orPage from "next/error"; import Container from "../../components/container"; import PostBody from "../../components/post-body"; import Header from "../../components/header"; import PostHeader from "../../components/post-header"; import Layout from "../../components/layout"; import { getPostBySlug, getAllPosts } from "...
ew}> <Container> <Header /> {router.isFallback ? ( <PostTitle>Loading…</PostTitle> ) : ( <> <article className="mb-32"> <Head> <title> {`${post.ti
nToHtml"; export default function Post({ post, morePosts, preview }) { const router = useRouter(); if (!router.isFallback && !post?.slug) { return <ErrorPage statusCode={404} />; } return ( <Layout preview={previ
{ "filepath": "examples/cms-tina/pages/posts/[slug].js", "language": "javascript", "file_size": 2146, "cut_index": 563, "middle_length": 229 }
import { NextResponse, type NextRequest } from "next/server"; import { hasEnvVars } from "../utils"; export async function updateSession(request: NextRequest) { let supabaseResponse = NextResponse.next({ request, }); // If the env vars are not set, skip proxy check. You can remove this // once you setup ...
}, setAll(cookiesToSet) { cookiesToSet.forEach(({ name, value }) => request.cookies.set(name, value), ); supabaseResponse = NextResponse.next({ request, }); cookiesToSet.
t. const supabase = createServerClient( process.env.NEXT_PUBLIC_SUPABASE_URL!, process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!, { cookies: { getAll() { return request.cookies.getAll();
{ "filepath": "examples/with-supabase/lib/supabase/proxy.ts", "language": "typescript", "file_size": 2659, "cut_index": 563, "middle_length": 229 }
from "next/head"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants"; export default function Meta() { return ( <Head> <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon.png" /> <link rel="icon" type="image/png" ...
vicons/favicon.ico" /> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-config" content="/favicons/browserconfig.xml" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="appli
/> <link rel="manifest" href="/favicons/site.webmanifest" /> <link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#000000" /> <link rel="shortcut icon" href="/fa
{ "filepath": "examples/cms-tina/components/meta.js", "language": "javascript", "file_size": 1262, "cut_index": 524, "middle_length": 229 }
t Link from "next/link"; import { Button } from "./ui/button"; import { createClient } from "@/lib/supabase/server"; import { LogoutButton } from "./logout-button"; export async function AuthButton() { const supabase = await createClient(); // You can also use getUser() which will be slower. const { data } = aw...
sName="flex gap-2"> <Button asChild size="sm" variant={"outline"}> <Link href="/auth/login">Sign in</Link> </Button> <Button asChild size="sm" variant={"default"}> <Link href="/auth/sign-up">Sign up</Link> </Button>
<div clas
{ "filepath": "examples/with-supabase/components/auth-button.tsx", "language": "tsx", "file_size": 805, "cut_index": 517, "middle_length": 14 }
import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import Link from "next/link"; import { useState } from "react"; ex...
Client(); setIsLoading(true); setError(null); try { // The url which will be included in the email. This URL needs to be configured in your redirect URLs in the Supabase dashboard at https://supabase.com/dashboard/project/_/auth/url-conf
ull>(null); const [success, setSuccess] = useState(false); const [isLoading, setIsLoading] = useState(false); const handleForgotPassword = async (e: React.FormEvent) => { e.preventDefault(); const supabase = create
{ "filepath": "examples/with-supabase/components/forgot-password-form.tsx", "language": "tsx", "file_size": 3564, "cut_index": 614, "middle_length": 229 }
import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import Link from "next/link"; import { useRouter } from "next/navig...
=> { e.preventDefault(); const supabase = createClient(); setIsLoading(true); setError(null); try { const { error } = await supabase.auth.signInWithPassword({ email, password, }); if (error) throw erro
ssword, setPassword] = useState(""); const [error, setError] = useState<string | null>(null); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const handleLogin = async (e: React.FormEvent)
{ "filepath": "examples/with-supabase/components/login-form.tsx", "language": "tsx", "file_size": 3526, "cut_index": 614, "middle_length": 229 }
role="img" viewBox="0 0 394 79" width="100" > <path d="M261.919 0.0330722H330.547V12.7H303.323V79.339H289.71V12.7H261.919V0.0330722Z" fill="currentColor" /> <path d="M149.052 0.0330722V12.7H94.0421V33.0772H138.281V45.7441H94.0421V66.6721H149.052V79.339H80...
ipRule="evenodd" d="M80.907 79.339L17.0151 0H0V79.3059H13.6121V16.9516L63.8067 79.339H80.907Z" fill="currentColor" fillRule="evenodd" /> <path d="M333.607 78.8546C332.61 78.8546 331.762 78.5093 331.052 77.8186C33
4184L206.352 28.6697L183.32 0.0661486Z" fill="currentColor" /> <path d="M201.6 56.7148L192.679 45.6229L165.455 79.4326H183.32L201.6 56.7148Z" fill="currentColor" /> <path cl
{ "filepath": "examples/with-supabase/components/next-logo.tsx", "language": "tsx", "file_size": 3993, "cut_index": 614, "middle_length": 229 }
/ui/button"; import { DropdownMenu, DropdownMenuContent, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { Laptop, Moon, Sun } from "lucide-react"; import { useTheme } from "next-themes"; import { useEffect, useState } from "react"; const The...
{theme === "light" ? ( <Sun key="light" size={ICON_SIZE} className={"text-muted-foreground"} /> ) : theme === "dark" ? ( <Moon key="dark"
ffect(() => { setMounted(true); }, []); if (!mounted) { return null; } const ICON_SIZE = 16; return ( <DropdownMenu> <DropdownMenuTrigger asChild> <Button variant="ghost" size={"sm"}>
{ "filepath": "examples/with-supabase/components/theme-switcher.tsx", "language": "tsx", "file_size": 2287, "cut_index": 563, "middle_length": 229 }
port { createClient } from "@/lib/supabase/client"; import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { useRout...
{ e.preventDefault(); const supabase = createClient(); setIsLoading(true); setError(null); try { const { error } = await supabase.auth.updateUser({ password }); if (error) throw error; // Update this route to redirect
assword] = useState(""); const [error, setError] = useState<string | null>(null); const [isLoading, setIsLoading] = useState(false); const router = useRouter(); const handleForgotPassword = async (e: React.FormEvent) =>
{ "filepath": "examples/with-supabase/components/update-password-form.tsx", "language": "tsx", "file_size": 2488, "cut_index": 563, "middle_length": 229 }
e = `create table notes ( id bigserial primary key, title text ); insert into notes(title) values ('Today I created a Supabase project.'), ('I added some data and queried it from Next.js.'), ('It was awesome!'); `.trim(); const rls = `alter table notes enable row level security; create policy "Allow public ...
mport { useEffect, useState } from 'react' export default function Page() { const [notes, setNotes] = useState<any[] | null>(null) const supabase = createClient() useEffect(() => { const getData = async () => { const { data } = await supa
reateClient() const { data: notes } = await supabase.from('notes').select() return <pre>{JSON.stringify(notes, null, 2)}</pre> } `.trim(); const client = `'use client' import { createClient } from '@/lib/supabase/client' i
{ "filepath": "examples/with-supabase/components/tutorial/fetch-data-steps.tsx", "language": "tsx", "file_size": 5000, "cut_index": 614, "middle_length": 229 }
* as React from "react"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const badgeVariants = cva( "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offse...
round", }, }, defaultVariants: { variant: "default", }, }, ); export interface BadgeProps extends React.HTMLAttributes<HTMLDivElement>, VariantProps<typeof badgeVariants> {} function Badge({ className, variant, ...props }:
ransparent bg-secondary text-secondary-foreground hover:bg-secondary/80", destructive: "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80", outline: "text-foreg
{ "filepath": "examples/with-supabase/components/ui/badge.tsx", "language": "tsx", "file_size": 1147, "cut_index": 518, "middle_length": 229 }
eact"; import { Slot } from "@radix-ui/react-slot"; import { cva, type VariantProps } from "class-variance-authority"; import { cn } from "@/lib/utils"; const buttonVariants = cva( "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline...
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground", secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80", ghost: "hover:bg-accent hover:text-accent-for
ant: { default: "bg-primary text-primary-foreground shadow hover:bg-primary/90", destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90", outline:
{ "filepath": "examples/with-supabase/components/ui/button.tsx", "language": "tsx", "file_size": 1915, "cut_index": 537, "middle_length": 229 }
b/utils"; const DropdownMenu = DropdownMenuPrimitive.Root; const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger; const DropdownMenuGroup = DropdownMenuPrimitive.Group; const DropdownMenuPortal = DropdownMenuPrimitive.Portal; const DropdownMenuSub = DropdownMenuPrimitive.Sub; const DropdownMenuRadioGroup = Dr...
gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0", inset && "pl-8", className, )} {...props} > {children} <ChevronRight
enuPrimitive.SubTrigger> & { inset?: boolean; } >(({ className, inset, children, ...props }, ref) => ( <DropdownMenuPrimitive.SubTrigger ref={ref} className={cn( "flex cursor-default select-none items-center
{ "filepath": "examples/with-supabase/components/ui/dropdown-menu.tsx", "language": "tsx", "file_size": 7647, "cut_index": 716, "middle_length": 229 }
import type { Metadata } from "next"; import { Geist } from "next/font/google"; import { ThemeProvider } from "next-themes"; import "./globals.css"; const defaultUrl = process.env.VERCEL_URL ? `https://${process.env.VERCEL_URL}` : "http://localhost:3000"; export const metadata: Metadata = { metadataBase: new UR...
`${geistSans.className} antialiased`}> <ThemeProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange > {children} </ThemeProvider> </body> <
ns", display: "swap", subsets: ["latin"], }); export default function RootLayout({ children, }: Readonly<{ children: React.ReactNode; }>) { return ( <html lang="en" suppressHydrationWarning> <body className={
{ "filepath": "examples/with-supabase/app/layout.tsx", "language": "tsx", "file_size": 1011, "cut_index": 512, "middle_length": 229 }
rom "@/components/deploy-button"; import { EnvVarWarning } from "@/components/env-var-warning"; import { AuthButton } from "@/components/auth-button"; import { ThemeSwitcher } from "@/components/theme-switcher"; import { hasEnvVars } from "@/lib/utils"; import Link from "next/link"; import { Suspense } from "react"; e...
"> <div className="flex gap-5 items-center font-semibold"> <Link href={"/"}>Next.js Supabase Starter</Link> <div className="flex items-center gap-2"> <DeployButton /> </div>
-1 w-full flex flex-col gap-20 items-center"> <nav className="w-full flex justify-center border-b border-b-foreground/10 h-16"> <div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm
{ "filepath": "examples/with-supabase/app/protected/layout.tsx", "language": "tsx", "file_size": 1883, "cut_index": 537, "middle_length": 229 }
from "next/link"; import { Button } from "./ui/button"; export function DeployButton() { return ( <> <Link href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%2Fexamples%2Fwith-supabase&project-name=nextjs-with-supabase&repository-name=nextj...
2Fexamples%2Fwith-supabase&demo-image=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2Fopengraph-image.png" target="_blank" > <Button className="flex items-center gap-2" size="sm"> <svg className="h-3 w-3"
+-+Client+Components%2C+Server+Components%2C+Route+Handlers%2C+Server+Actions+and+Middleware.&demo-url=https%3A%2F%2Fdemo-nextjs-with-supabase.vercel.app%2F&external-id=https%3A%2F%2Fgithub.com%2Fvercel%2Fnext.js%2Ftree%2Fcanary%
{ "filepath": "examples/with-supabase/components/deploy-button.tsx", "language": "tsx", "file_size": 1321, "cut_index": 524, "middle_length": 229 }
import { Button } from "@/components/ui/button"; import { Card, CardContent, CardDescription, CardHeader, CardTitle, } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import Link from "next/link"; import { useRouter } from "next/navig...
eRouter(); const handleSignUp = async (e: React.FormEvent) => { e.preventDefault(); const supabase = createClient(); setIsLoading(true); setError(null); if (password !== repeatPassword) { setError("Passwords do not match");
assword, setPassword] = useState(""); const [repeatPassword, setRepeatPassword] = useState(""); const [error, setError] = useState<string | null>(null); const [isLoading, setIsLoading] = useState(false); const router = us
{ "filepath": "examples/with-supabase/components/sign-up-form.tsx", "language": "tsx", "file_size": 3825, "cut_index": 614, "middle_length": 229 }
; import { useState } from "react"; import { Button } from "../ui/button"; const CopyIcon = () => ( <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" ...
oints="20 6 9 17 4 12"></polyline> </svg> ); export function CodeBlock({ code }: { code: string }) { const [icon, setIcon] = useState(CopyIcon); const copy = async () => { await navigator?.clipboard?.writeText(code); setIcon(CheckIcon);
xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" > <polyline p
{ "filepath": "examples/with-supabase/components/tutorial/code-block.tsx", "language": "tsx", "file_size": 1365, "cut_index": 524, "middle_length": 229 }
from "lucide-react"; export function SignUpUserSteps() { return ( <ol className="flex flex-col gap-6"> {process.env.VERCEL_ENV === "preview" || process.env.VERCEL_ENV === "production" ? ( <TutorialStep title="Set up redirect urls"> <p>It looks like this App is hosted on Vercel.</p> ...
-secondary-foreground border"> https://{process.env.VERCEL_URL} </span> . </p> <p className="mt-4"> You will need to{" "} <Link className="text-primary hover:te
dary-foreground border"> &quot;{process.env.VERCEL_ENV}&quot; </span>{" "} on <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text
{ "filepath": "examples/with-supabase/components/tutorial/sign-up-user-steps.tsx", "language": "tsx", "file_size": 3606, "cut_index": 614, "middle_length": 229 }
use client"; import * as React from "react"; import * as CheckboxPrimitive from "@radix-ui/react-checkbox"; import { Check } from "lucide-react"; import { cn } from "@/lib/utils"; const Checkbox = React.forwardRef< React.ElementRef<typeof CheckboxPrimitive.Root>, React.ComponentPropsWithoutRef<typeof CheckboxPri...
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")} > <Check className="h-4 w-4" /> </CheckboxPrimitive.Indicator> </CheckboxPrimitive.Root> )); Checkbox.displayName = CheckboxPrimitive.Roo
:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground", className, )} {...props} >
{ "filepath": "examples/with-supabase/components/ui/checkbox.tsx", "language": "tsx", "file_size": 1035, "cut_index": 513, "middle_length": 229 }
utton"; import { EnvVarWarning } from "@/components/env-var-warning"; import { AuthButton } from "@/components/auth-button"; import { Hero } from "@/components/hero"; import { ThemeSwitcher } from "@/components/theme-switcher"; import { ConnectSupabaseSteps } from "@/components/tutorial/connect-supabase-steps"; import ...
-b-foreground/10 h-16"> <div className="w-full max-w-5xl flex justify-between items-center p-3 px-5 text-sm"> <div className="flex gap-5 items-center font-semibold"> <Link href={"/"}>Next.js Supabase Starter</Link>
unction Home() { return ( <main className="min-h-screen flex flex-col items-center"> <div className="flex-1 w-full flex flex-col gap-20 items-center"> <nav className="w-full flex justify-center border-b border
{ "filepath": "examples/with-supabase/app/page.tsx", "language": "tsx", "file_size": 2246, "cut_index": 563, "middle_length": 229 }
tLogo } from "./next-logo"; import { SupabaseLogo } from "./supabase-logo"; export function Hero() { return ( <div className="flex flex-col gap-16 items-center"> <div className="flex gap-8 justify-center items-center"> <a href="https://supabase.com/?utm_source=create-next-app&utm_medium=t...
ng-tight mx-auto max-w-xl text-center"> The fastest way to build apps with{" "} <a href="https://supabase.com/?utm_source=create-next-app&utm_medium=template&utm_term=nextjs" target="_blank" className="font-bol
ref="https://nextjs.org/" target="_blank" rel="noreferrer"> <NextLogo /> </a> </div> <h1 className="sr-only">Supabase and Next.js Starter Template</h1> <p className="text-3xl lg:text-4xl !leadi
{ "filepath": "examples/with-supabase/components/hero.tsx", "language": "tsx", "file_size": 1451, "cut_index": 524, "middle_length": 229 }
port function ConnectSupabaseSteps() { return ( <ol className="flex flex-col gap-6"> <TutorialStep title="Create Supabase project"> <p> Head over to{" "} <a href="https://app.supabase.com/project/_/settings/api" target="_blank" className="font-...
ndary-foreground border"> .env.example </span>{" "} file in your Next.js app to{" "} <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-secondary-foreground border
/TutorialStep> <TutorialStep title="Declare environment variables"> <p> Rename the{" "} <span className="relative rounded bg-muted px-[0.3rem] py-[0.2rem] font-mono text-xs font-medium text-seco
{ "filepath": "examples/with-supabase/components/tutorial/connect-supabase-steps.tsx", "language": "tsx", "file_size": 2128, "cut_index": 563, "middle_length": 229 }
vg" > <g clipPath="url(#clip0_4671_51136)"> <g clipPath="url(#clip1_4671_51136)"> <path d="M13.4028 21.8652C12.8424 22.5629 11.7063 22.1806 11.6928 21.2898L11.4954 8.25948H20.3564C21.9614 8.25948 22.8565 10.0924 21.8585 11.3353L13.4028 21.8652Z" fill="url(#paint0_line...
H2.84528C1.24026 14.5041 0.345103 12.6711 1.34316 11.4283L9.79895 0.89838Z" fill="#3ECF8E" /> </g> <path d="M30.5894 13.3913C30.7068 14.4766 31.7052 16.3371 34.6026 16.3371C37.1279 16.3371 38.3418 14.7479 38.
3353L13.4028 21.8652Z" fill="url(#paint1_linear_4671_51136)" fillOpacity="0.2" /> <path d="M9.79895 0.89838C10.3593 0.200591 11.4954 0.582929 11.5089 1.47383L11.5955 14.5041
{ "filepath": "examples/with-supabase/components/supabase-logo.tsx", "language": "tsx", "file_size": 7226, "cut_index": 716, "middle_length": 229 }
eact"; import { cn } from "@/lib/utils"; const Card = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...props }, ref) => ( <div ref={ref} className={cn( "rounded-xl border bg-card text-card-foreground shadow", className, )} {...props} /> )); ...
rops }, ref) => ( <div ref={ref} className={cn("font-semibold leading-none tracking-tight", className)} {...props} /> )); CardTitle.displayName = "CardTitle"; const CardDescription = React.forwardRef< HTMLDivElement, React.HTMLAttribut
me={cn("flex flex-col space-y-1.5 p-6", className)} {...props} /> )); CardHeader.displayName = "CardHeader"; const CardTitle = React.forwardRef< HTMLDivElement, React.HTMLAttributes<HTMLDivElement> >(({ className, ...p
{ "filepath": "examples/with-supabase/components/ui/card.tsx", "language": "tsx", "file_size": 1857, "cut_index": 537, "middle_length": 229 }
{ Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Suspense } from "react"; async function ErrorContent({ searchParams, }: { searchParams: Promise<{ error: string }>; }) { const params = await searchParams; return ( <> {params?.error ? ( <p className="text-sm...
<div className="w-full max-w-sm"> <div className="flex flex-col gap-6"> <Card> <CardHeader> <CardTitle className="text-2xl"> Sorry, something went wrong. </CardTitle> </
p> )} </> ); } export default function Page({ searchParams, }: { searchParams: Promise<{ error: string }>; }) { return ( <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10">
{ "filepath": "examples/with-supabase/app/auth/error/page.tsx", "language": "tsx", "file_size": 1244, "cut_index": 518, "middle_length": 229 }
ents/ui/card"; export default function Page() { return ( <div className="flex min-h-svh w-full items-center justify-center p-6 md:p-10"> <div className="w-full max-w-sm"> <div className="flex flex-col gap-6"> <Card> <CardHeader> <CardTitle className="text-2xl"> ...
foreground"> You&apos;ve successfully signed up. Please check your email to confirm your account before signing in. </p> </CardContent> </Card> </div> </div> </div> );
ent> <p className="text-sm text-muted-
{ "filepath": "examples/with-supabase/app/auth/sign-up-success/page.tsx", "language": "tsx", "file_size": 916, "cut_index": 606, "middle_length": 52 }
{ throw new Error('Invalid/Missing environment variable: "MONGODB_URI"'); } const uri = process.env.MONGODB_URI; const options = { appName: "devrel.template.nextjs" }; let client: MongoClient; if (process.env.NODE_ENV === "development") { // In development mode, use a global variable so that the value // is pr...
ngoClient(uri, options); } client = globalWithMongo._mongoClient; } else { // In production mode, it's best to not use a global variable. client = new MongoClient(uri, options); } // Export a module-scoped MongoClient. By doing this in a // separa
oClient) { globalWithMongo._mongoClient = new Mo
{ "filepath": "examples/with-mongodb/lib/mongodb.ts", "language": "typescript", "file_size": 968, "cut_index": 582, "middle_length": 52 }
from "next"; type ConnectionStatus = { isConnected: boolean; }; const inter = Inter({ subsets: ["latin"] }); export const getServerSideProps: GetServerSideProps< ConnectionStatus > = async () => { try { await client.connect(); // `await client.connect()` will use the default database passed in the MONGODB_...
10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"> <p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zinc-200 pb-6 pt-8 backdrop-blur-2xl dark:border-neutral-800 dar
{ isConnected, }: InferGetServerSidePropsType<typeof getServerSideProps>) { return ( <main className={`flex min-h-screen flex-col items-center justify-between p-24 ${inter.className}`} > <div className="z-
{ "filepath": "examples/with-mongodb/pages/index.tsx", "language": "tsx", "file_size": 8135, "cut_index": 716, "middle_length": 229 }
goose"; export interface Pets extends mongoose.Document { name: string; owner_name: string; species: string; age: number; poddy_trained: boolean; diet: string[]; image_url: string; likes: string[]; dislikes: string[]; } /* PetSchema will correspond to a collection in your MongoDB database. */ const ...
ers"], }, species: { /* The species of your pet */ type: String, required: [true, "Please specify the species of your pet."], maxlength: [40, "Species specified cannot be more than 40 characters"], }, age: { /* Pet's age, if ap
t be more than 60 characters"], }, owner_name: { /* The owner of this pet */ type: String, required: [true, "Please provide the pet owner's name"], maxlength: [60, "Owner's Name cannot be more than 60 charact
{ "filepath": "examples/with-mongodb-mongoose/models/Pet.ts", "language": "typescript", "file_size": 1631, "cut_index": 537, "middle_length": 229 }
"../lib/dbConnect"; import Pet, { Pets } from "../models/Pet"; import { GetServerSideProps } from "next"; type Props = { pets: Pets[]; }; const Index = ({ pets }: Props) => { return ( <> {pets.map((pet) => ( <div key={pet._id}> <div className="card"> <img src={pet.image_ur...
data, index) => ( <li key={index}>{data} </li> ))} </ul> </div> <div className="dislikes info"> <p className="label">Dislikes</p> <ul>
ner: {pet.owner_name}</p> {/* Extra Pet Info: Likes and Dislikes */} <div className="likes info"> <p className="label">Likes</p> <ul> {pet.likes.map((
{ "filepath": "examples/with-mongodb-mongoose/pages/index.tsx", "language": "tsx", "file_size": 2160, "cut_index": 563, "middle_length": 229 }
r } from "next/router"; import Link from "next/link"; import dbConnect from "@/lib/dbConnect"; import Pet, { Pets } from "@/models/Pet"; import { GetServerSideProps, GetServerSidePropsContext } from "next"; import { ParsedUrlQuery } from "querystring"; interface Params extends ParsedUrlQuery { id: string; } type Pr...
"Failed to delete the pet."); } }; return ( <div key={pet._id}> <div className="card"> <img src={pet.image_url} /> <h5 className="pet-name">{pet.name}</h5> <div className="main-content"> <p className="pe
""); const handleDelete = async () => { const petID = router.query.id; try { await fetch(`/api/pets/${petID}`, { method: "Delete", }); router.push("/"); } catch (error) { setMessage(
{ "filepath": "examples/with-mongodb-mongoose/pages/[id]/index.tsx", "language": "tsx", "file_size": 2613, "cut_index": 563, "middle_length": 229 }
"; import Pet from "@/models/Pet"; export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const { method } = req; await dbConnect(); switch (method) { case "GET": try { const pets = await Pet.find({}); /* find all the data in our database */ res.stat...
ate a new model in the database */ res.status(201).json({ success: true, data: pet }); } catch (error) { res.status(400).json({ success: false }); } break; default: res.status(400).json({ success: false });
it Pet.create( req.body, ); /* cre
{ "filepath": "examples/with-mongodb-mongoose/pages/api/pets/index.ts", "language": "typescript", "file_size": 928, "cut_index": 606, "middle_length": 52 }
t Header from "./header"; type LayoutProps = { user?: any; loading?: boolean; children: React.ReactNode; }; const Layout = ({ user, loading = false, children }: LayoutProps) => { return ( <> <Head> <title>Next.js with Auth0</title> </Head> <Header user={user} loading={loading} /...
body { margin: 0; color: #333; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } `}</style> <
`}</style> <style jsx global>{`
{ "filepath": "examples/auth0/components/layout.tsx", "language": "tsx", "file_size": 890, "cut_index": 547, "middle_length": 52 }
om "../components/layout"; const Home = () => { const { user, isLoading } = useUser(); return ( <Layout user={user} loading={isLoading}> <h1>Next.js and Auth0 Example</h1> {isLoading && <p>Loading login info...</p>} {!isLoading && !user && ( <> <p> To test the...
</p> </> )} {user && ( <> <h4>Rendered user info on the client</h4> <img src={user.picture} alt="user picture" /> <p>nickname: {user.nickname}</p> <p>name: {user.name}</p>
red profile pages, and <i>Logout</i>
{ "filepath": "examples/auth0/pages/index.tsx", "language": "tsx", "file_size": 971, "cut_index": 582, "middle_length": 52 }
rs from "cors"; // Initializing the cors middleware // You can read more about the available options here: https://github.com/expressjs/cors#configuration-options const cors = Cors({ methods: ["POST", "GET", "HEAD"], }); // Helper method to wait for a middleware to execute before continuing // And to throw an error...
{ return reject(result); } return resolve(result); }); }); } export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { // Run the middleware await runMiddleware(req, res, cors); // Rest of
result: any) => { if (result instanceof Error)
{ "filepath": "examples/api-routes-cors/pages/api/cors.ts", "language": "typescript", "file_size": 951, "cut_index": 582, "middle_length": 52 }
n(); return ( <main className="flex min-h-screen flex-col items-center justify-between p-24"> <div className="z-10 max-w-5xl w-full items-center justify-between font-mono text-sm lg:flex"> <p className="fixed left-0 top-0 flex w-full justify-center border-b border-gray-300 bg-gradient-to-b from-zin...
adient-to-t from-white via-white dark:from-black dark:via-black lg:static lg:h-auto lg:w-auto lg:bg-none"> <a className="pointer-events-none flex place-items-center gap-2 p-8 lg:pointer-events-auto lg:p-0" href="https://ve
App Router: Get started by editing&nbsp; <code className="font-mono font-bold">app/app-demo/page.tsx</code> </p> <div className="fixed bottom-0 left-0 flex h-48 w-full items-end justify-center bg-gr
{ "filepath": "examples/with-mongodb/app/app-demo/page.tsx", "language": "tsx", "file_size": 7500, "cut_index": 716, "middle_length": 229 }
ter"; import useSWR from "swr"; import Form from "@/components/Form"; const fetcher = (url: string) => fetch(url) .then((res) => res.json()) .then((json) => json.data); const EditPet = () => { const router = useRouter(); const { id } = router.query; const { data: pet, error, isLoading, }...
ies: pet.species, age: pet.age, poddy_trained: pet.poddy_trained, diet: pet.diet, image_url: pet.image_url, likes: pet.likes, dislikes: pet.dislikes, }; return <Form formId="edit-pet-form" petForm={petForm} forNewPet={false} />
: pet.name, owner_name: pet.owner_name, spec
{ "filepath": "examples/with-mongodb-mongoose/pages/[id]/edit.tsx", "language": "tsx", "file_size": 885, "cut_index": 547, "middle_length": 52 }
nk"; type HeaderProps = { user?: any; loading: boolean; }; const Header = ({ user, loading }: HeaderProps) => { return ( <header> <nav> <ul> <li> <Link href="/">Home</Link> </li> <li> <Link href="/about">About</Link> </li> ...
red profile (advanced) </Link> </li> <li> <a href="/api/auth/logout">Logout</a> </li> </> ) : ( <li> <a href="/api/a
<> <li> <Link href="/profile">Client rendered profile</Link> </li> <li> <Link href="/advanced/ssr-profile"> Server rende
{ "filepath": "examples/auth0/components/header.tsx", "language": "tsx", "file_size": 1897, "cut_index": 537, "middle_length": 229 }
ongoose"; declare global { var mongoose: any; // This must be a `var` and not a `let / const` } let cached = global.mongoose; if (!cached) { cached = global.mongoose = { conn: null, promise: null }; } async function dbConnect() { const MONGODB_URI = process.env.MONGODB_URI!; if (!MONGODB_URI) { throw ne...
se = mongoose.connect(MONGODB_URI, opts).then((mongoose) => { return mongoose; }); } try { cached.conn = await cached.promise; } catch (e) { cached.promise = null; throw e; } return cached.conn; } export default dbConnect;
bufferCommands: false, }; cached.promi
{ "filepath": "examples/with-mongodb-mongoose/lib/dbConnect.ts", "language": "typescript", "file_size": 844, "cut_index": 535, "middle_length": 52 }
NextApiResponse } from "next"; import dbConnect from "@/lib/dbConnect"; import Pet from "@/models/Pet"; export default async function handler( req: NextApiRequest, res: NextApiResponse, ) { const { query: { id }, method, } = req; await dbConnect(); switch (method) { case "GET" /* Get a model ...
d, req.body, { new: true, runValidators: true, }); if (!pet) { return res.status(400).json({ success: false }); } res.status(200).json({ success: true, data: pet }); } catch (error) {
ccess: true, data: pet }); } catch (error) { res.status(400).json({ success: false }); } break; case "PUT" /* Edit a model by its ID */: try { const pet = await Pet.findByIdAndUpdate(i
{ "filepath": "examples/with-mongodb-mongoose/pages/api/pets/[id].ts", "language": "typescript", "file_size": 1544, "cut_index": 537, "middle_length": 229 }
dy_trained: boolean; diet: string[]; image_url: string; likes: string[]; dislikes: string[]; } interface Error { name?: string; owner_name?: string; species?: string; image_url?: string; } type Props = { formId: string; petForm: FormData; forNewPet?: boolean; }; const Form = ({ formId, petForm,...
url: petForm.image_url, likes: petForm.likes, dislikes: petForm.dislikes, }); /* The PUT method edits an existing entry in the mongodb database. */ const putData = async (form: FormData) => { const { id } = router.query; try {
); const [form, setForm] = useState({ name: petForm.name, owner_name: petForm.owner_name, species: petForm.species, age: petForm.age, poddy_trained: petForm.poddy_trained, diet: petForm.diet, image_
{ "filepath": "examples/with-mongodb-mongoose/components/Form.tsx", "language": "tsx", "file_size": 5615, "cut_index": 716, "middle_length": 229 }
import { createClient } from "@/lib/supabase/server"; import { type EmailOtpType } from "@supabase/supabase-js"; import { redirect } from "next/navigation"; import { type NextRequest } from "next/server"; export async function GET(request: NextRequest) { const { searchParams } = new URL(request.url); const token_h...
} else { // redirect the user to an error page with some instructions redirect(`/auth/error?error=${error?.message}`); } } // redirect the user to an error page with some instructions redirect(`/auth/error?error=No token hash or ty
abase = await createClient(); const { error } = await supabase.auth.verifyOtp({ type, token_hash, }); if (!error) { // redirect user to specified redirect URL or root of app redirect(next);
{ "filepath": "examples/with-supabase/app/auth/confirm/route.ts", "language": "typescript", "file_size": 1005, "cut_index": 512, "middle_length": 229 }
from "next/head"; import { CMS_NAME, HOME_OG_IMAGE_URL } from "../lib/constants"; export default function Meta() { return ( <Head> <link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png" /> <link rel="icon" type="image/png" ...
/favicon.ico" /> <meta name="msapplication-TileColor" content="#000000" /> <meta name="msapplication-config" content="/favicon/browserconfig.xml" /> <meta name="theme-color" content="#000" /> <link rel="alternate" type="application/
/> <link rel="manifest" href="/favicon/site.webmanifest" /> <link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#000000" /> <link rel="shortcut icon" href="/favicon
{ "filepath": "examples/cms-drupal/components/meta.js", "language": "javascript", "file_size": 1255, "cut_index": 524, "middle_length": 229 }
xport default function Form() { const [message, setMessage] = useState(""); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); analytics.track("Form Submitted", { message, }); setMessage(""); }; return ( <> <form onSubmit={handleSubmit}> <label> ...
label span { display: block; margin-bottom: 12px; } textarea { min-width: 300px; min-height: 120px; } button { margin-top: 12px; display: block; }
mit</button> </form> <style jsx>{`
{ "filepath": "examples/with-segment-analytics/components/form.tsx", "language": "tsx", "file_size": 943, "cut_index": 606, "middle_length": 52 }
ort type { InferGetStaticPropsType } from "next"; import Link from "next/link"; import Container from "../../components/container"; import distanceToNow from "../../lib/dateRelative"; import { getAllPosts } from "../../lib/getPost"; export default function NotePage({ allPosts, }: InferGetStaticPropsType<typeof getSt...
ame="text-gray-400"> <time>{distanceToNow(new Date(post.date))}</time> </div> </article> )) ) : ( <p>No blog posted yet :/</p> )} </Container> ); } export async function getStaticProps(
/posts/${post.slug}`} href="/posts/[slug]" className="text-lg leading-6 font-bold" > {post.title} </Link> <p>{post.excerpt}</p> <div classN
{ "filepath": "examples/blog-with-comment/pages/posts/index.tsx", "language": "tsx", "file_size": 1118, "cut_index": 515, "middle_length": 229 }
"https://graphcms.com/"; export const HOME_OG_IMAGE_URL = "https://og-image.vercel.app/Next.js%20Blog%20Example%20with%20**GraphCMS**.png?theme=light&md=1&fontSize=75px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fnextjs-black-logo.svg&images=data%3Aimage%2Fsvg%2Bxml%3Bbase64%2...
Ljk1YTEzLjMgMTMuMyAwIDAxLTUuNjUtNS43NWw2LjU2LTRjMS41MiAyLjk2IDQuMTMgNC40NCA3Ljg0IDQuNDQgMi40NCAwIDQuMzUtLjY3IDUuNzUtMi4wMiAxLjQtMS4zNSAyLjEtMy4yNyAyLjEtNS43NnYtMy40MmMtMi4yOCAzLjItNS40NyA0LjgtOS41OCA0LjgtNC4wMS4xLTcuODctMS42Mi0xMC42LTQuN0ExNi40NCAxNi40NCAw
xNy40Ni0xMFYzNWwtOC43MyA1VjMwbDE3LjQ2LTEwdjMwTC4zNSA3MGw4LjczIDVMNDQgNTVWNWwtOC43My01eiIvPjxwYXRoIGQ9Ik04OC40NSAyMC45MUg5NnYzMC4wNmMwIDQuODgtMS41MyA4LjYtNC41OCAxMS4xN0ExNi42IDE2LjYgMCAwMTgwLjM3IDY2Yy0yLjk0LjA3LTUuODYtLjYtOC41MS0x
{ "filepath": "examples/cms-graphcms/lib/constants.js", "language": "javascript", "file_size": 5026, "cut_index": 614, "middle_length": 229 }
Container from "./container"; import { EXAMPLE_PATH } from "../lib/constants"; export default function Footer() { return ( <footer className="bg-accent-1 border-t border-accent-2"> <Container> <div className="py-28 flex flex-col lg:flex-row items-center"> <h3 className="text-4xl lg:text-...
er border-black text-white font-bold py-3 px-12 lg:px-8 duration-200 transition-colors mb-6 lg:mb-0" > Read Documentation </a> <a href={`https://github.com/vercel/next.js/tree/canary/examples/
flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2"> <a href="https://nextjs.org/docs/basic-features/pages" className="mx-3 bg-black hover:bg-white hover:text-black bord
{ "filepath": "examples/cms-graphcms/components/footer.js", "language": "javascript", "file_size": 1210, "cut_index": 518, "middle_length": 229 }
import Avatar from "../components/avatar"; import Date from "../components/date"; import CoverImage from "../components/cover-image"; import Link from "next/link"; export default function HeroPost({ title, coverImage, date, excerpt, author, slug, }) { return ( <section> <div className="mb-8 md:...
-lg md:mb-0"> <Date dateString={date} /> </div> </div> <div> <p className="mb-4 text-lg leading-relaxed">{excerpt}</p> <Avatar name={author.name} picture={author.picture.url} /> </div>
<h3 className="mb-4 text-4xl leading-tight lg:text-6xl"> <Link href={`/posts/${slug}`} className="hover:underline"> {title} </Link> </h3> <div className="mb-4 text
{ "filepath": "examples/cms-graphcms/components/hero-post.js", "language": "javascript", "file_size": 1027, "cut_index": 512, "middle_length": 229 }
import { images } from "../constants"; const transition = { duration: 0.5, ease: [0.43, 0.13, 0.23, 0.96] }; const thumbnailVariants = { initial: { scale: 0.9, opacity: 0 }, enter: { scale: 1, opacity: 1, transition }, exit: { scale: 0.5, opacity: 0, transition: { duration: 1.5, ...transition }, ...
scroll={false}> <motion.img src={`https://images.unsplash.com/${id}?auto=format&fit=crop&w=1500`} alt="The Barbican" variants={imageVariants} transition={transition} /> </Link>
variants={thumbnailVariants}> <motion.div className="frame" whileHover="hover" variants={frameVariants} transition={transition} > <Link href="/image/[index]" as={`/image/${i}`}
{ "filepath": "examples/with-framer-motion/components/Gallery.js", "language": "javascript", "file_size": 3310, "cut_index": 614, "middle_length": 229 }
port { AnimatePresence } from "framer-motion"; import { useRouter } from "next/router"; function handleExitComplete() { if (typeof window !== "undefined") { window.scrollTo({ top: 0 }); } } function MyApp({ Component, pageProps }) { const router = useRouter(); return ( <> <AnimatePresence exitBe...
: 0; background: #f9fbf8; } * { box-sizing: border-box; font-family: Helvetica, sans-serif; font-weight: 900; color: #222; } `} </style> </> ); } export default M
margin
{ "filepath": "examples/with-framer-motion/pages/_app.js", "language": "javascript", "file_size": 790, "cut_index": 514, "middle_length": 14 }
rom "../interfaces"; import React, { useState } from "react"; import useSWR from "swr"; import { useAuth0 } from "@auth0/auth0-react"; const fetcher = (url) => fetch(url).then((res) => { if (res.ok) { return res.json(); } throw new Error(`${res.status} ${res.statusText} while fetching: ${url}`); ...
ent", { method: "POST", body: JSON.stringify({ text }), headers: { Authorization: token, "Content-Type": "application/json", }, }); setText(""); await mutate(); } catch (err) {
"/api/comment", fetcher, { fallbackData: [] }, ); const onSubmit = async (e: React.FormEvent) => { e.preventDefault(); const token = await getAccessTokenSilently(); try { await fetch("/api/comm
{ "filepath": "examples/blog-with-comment/hooks/useComment.ts", "language": "typescript", "file_size": 1524, "cut_index": 537, "middle_length": 229 }
{ NextApiRequest, NextApiResponse } from "next"; import type { User, Comment } from "../interfaces"; import redis from "./redis"; import getUser from "./getUser"; import clearUrl from "./clearUrl"; export default async function deleteComments( req: NextApiRequest, res: NextApiResponse, ) { const url = clearUrl(r...
; if (!user) return res.status(400).json({ message: "Invalid token." }); comment.user.email = user.email; const isAdmin = process.env.NEXT_PUBLIC_AUTH0_ADMIN_EMAIL === user.email; const isAuthor = user.sub === comment.user.sub; if (!i
.json({ message: "Missing parameter." }); } if (!redis) { return res.status(500).json({ message: "Failed to connect to redis." }); } try { // verify user token const user: User = await getUser(authorization)
{ "filepath": "examples/blog-with-comment/lib/deleteComment.ts", "language": "typescript", "file_size": 1266, "cut_index": 524, "middle_length": 229 }
type { Post } from "../interfaces"; import fs from "fs"; import { join } from "path"; import matter from "gray-matter"; const postsDirectory = join(process.cwd(), "_posts"); export function getPostSlugs() { return fs.readdirSync(postsDirectory); } export function getPostBySlug(slug: string, fields: string[] = [])...
items[field] = content; } if (typeof data[field] !== "undefined") { items[field] = data[field]; } }); return items; } export function getAllPosts(fields: string[] = []) { const slugs = getPostSlugs(); const posts = slugs
= matter(fileContents); const items: Post = {}; // Ensure only the minimal needed data is exposed fields.forEach((field) => { if (field === "slug") { items[field] = realSlug; } if (field === "content") {
{ "filepath": "examples/blog-with-comment/lib/getPost.ts", "language": "typescript", "file_size": 1181, "cut_index": 518, "middle_length": 229 }
rom "../../interfaces"; import distanceToNow from "../../lib/dateRelative"; import { useAuth0 } from "@auth0/auth0-react"; type CommentListProps = { comments?: Comment[]; onDelete: (comment: Comment) => Promise<void>; }; export default function CommentList({ comments, onDelete }: CommentListProps) { const { use...
ink-0"> <img src={comment.user.picture} alt={comment.user.name} width={40} height={40} className="rounded-full" /> </div
const isAdmin = user && user.email === process.env.NEXT_PUBLIC_AUTH0_ADMIN_EMAIL; return ( <div key={comment.created_at} className="flex space-x-4"> <div className="flex-shr
{ "filepath": "examples/blog-with-comment/components/comment/list.tsx", "language": "tsx", "file_size": 1778, "cut_index": 537, "middle_length": 229 }
mport "tailwindcss/tailwind.css"; import type { AppProps } from "next/app"; import Head from "next/head"; import Header from "../components/header"; import { Auth0Provider } from "@auth0/auth0-react"; export default function MyApp({ Component, pageProps }: AppProps) { return ( <Auth0Provider clientId={pro...
tent="Clone and deploy your own Next.js portfolio in minutes." /> <title>My awesome blog</title> </Head> <Header /> <main className="py-14"> <Component {...pageProps} /> </main> </Auth0Provider> ); }
<meta name="description" con
{ "filepath": "examples/blog-with-comment/pages/_app.tsx", "language": "tsx", "file_size": 821, "cut_index": 513, "middle_length": 52 }
@auth0/nextjs-auth0/client"; import Layout from "../../components/layout"; const ApiProfile = () => { const { user, isLoading } = useUser(); const [data, setData] = useState(null); useEffect(() => { (async () => { const res = await fetch("/api/protected-api"); const data = await res.json(); ...
<p>By making request to '/api/protected-api' serverless function</p> <p>so without a valid session cookie will fail</p> <p>{JSON.stringify(data)}</p> </div> </Layout> ); }; // Public route.(CSR) also accessing API from the cli
e are fetching data on the client-side :</p>
{ "filepath": "examples/auth0/pages/advanced/api-profile.tsx", "language": "tsx", "file_size": 981, "cut_index": 582, "middle_length": 52 }
nt-side rendering import { useState } from "react"; import Header from "./_components/Header"; // Adjust the path based on your directory structure import dynamic from "next/dynamic"; const DynamicComponent1 = dynamic(() => import("./_components/hello1")); const DynamicComponent2WithCustomLoading = dynamic( () => ...
"Joe", "Bel", "Max", "Lee"]; export default function IndexPage() { const [showMore, setShowMore] = useState(false); const [falsyField] = useState(false); const [results, setResults] = useState(); return ( <div> <Header /> {/* Loa
, { loading: () => <p>Loading ...</p>, ssr: false }, ); const DynamicComponent4 = dynamic(() => import("./_components/hello4")); const DynamicComponent5 = dynamic(() => import("./_components/hello5")); const names = ["Tim",
{ "filepath": "examples/with-dynamic-import/app/page.tsx", "language": "tsx", "file_size": 2082, "cut_index": 563, "middle_length": 229 }
{ NextApiRequest, NextApiResponse } from "next"; import type { Comment } from "../interfaces"; import redis from "./redis"; import { nanoid } from "nanoid"; import getUser from "./getUser"; import clearUrl from "./clearUrl"; export default async function createComments( req: NextApiRequest, res: NextApiResponse, )...
); if (!user) return res.status(400).json({ message: "Need authorization." }); const { name, picture, sub, email } = user; const comment: Comment = { id: nanoid(), created_at: Date.now(), url, text, user: { name,
e: "Missing parameter." }); } if (!redis) { return res .status(400) .json({ message: "Failed to connect to redis client." }); } try { // verify user token const user = await getUser(authorization
{ "filepath": "examples/blog-with-comment/lib/createComment.ts", "language": "typescript", "file_size": 1253, "cut_index": 524, "middle_length": 229 }
"@auth0/auth0-react"; type CommentFormProps = { text: string; setText: Function; onSubmit: (e: React.FormEvent) => Promise<void>; }; export default function CommentForm({ text, setText, onSubmit, }: CommentFormProps) { const { isAuthenticated, logout, loginWithPopup } = useAuth0(); return ( <form...
/> <div className="flex items-center mt-4"> {isAuthenticated ? ( <div className="flex items-center space-x-6"> <button className="py-2 px-4 rounded bg-blue-600 text-white disabled:opacity-40 hover:bg-blue-700">
isAuthenticated ? `What are your thoughts?` : "Please login to leave a comment" } onChange={(e) => setText(e.target.value)} value={text} disabled={!isAuthenticated}
{ "filepath": "examples/blog-with-comment/components/comment/form.tsx", "language": "tsx", "file_size": 1567, "cut_index": 537, "middle_length": 229 }
* @type {import('tailwindcss').Config} */ module.exports = { content: [ "./pages/**/*.{js,ts,jsx,tsx}", "./components/**/*.{js,ts,jsx,tsx}", ], theme: { extend: { colors: { "accent-1": "#FAFAFA", "accent-2": "#EAEAEA", "accent-7": "#333", success: "#0070f3", ...
"5xl": "2.5rem", "6xl": "2.75rem", "7xl": "4.5rem", "8xl": "6.25rem", }, boxShadow: { small: "0 5px 10px rgba(0, 0, 0, 0.12)", medium: "0 8px 30px rgba(0, 0, 0, 0.12)", }, }, }, plugins:
tSize: {
{ "filepath": "examples/cms-graphcms/tailwind.config.js", "language": "javascript", "file_size": 791, "cut_index": 514, "middle_length": 14 }