prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
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-graphcms/components/alert.js",
"language": "javascript",
"file_size": 1203,
"cut_index": 518,
"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-graphcms/components/meta.js",
"language": "javascript",
"file_size": 1255,
"cut_index": 524,
"middle_length": 229
} |
m "../components/avatar";
import Date from "../components/date";
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="h... | sName="max-w-2xl mx-auto">
<div className="block mb-6 md:hidden">
<Avatar name={author.name} picture={author.picture.url} />
</div>
<div className="mb-6 text-lg">
<Date dateString={date} />
</div>
< | url={coverImage.url} />
</div>
<div clas | {
"filepath": "examples/cms-graphcms/components/post-header.js",
"language": "javascript",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
ault async function handler(req, res) {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
if (
req.query.secret !== process.env.GRAPHCMS_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
}
// ... | ssage: "Invalid slug" });
}
// Enable Draft 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 redirect vulnerabilities
|
if (!post) {
return res.status(401).json({ me | {
"filepath": "examples/cms-graphcms/pages/api/preview.js",
"language": "javascript",
"file_size": 964,
"cut_index": 582,
"middle_length": 52
} |
* @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-drupal/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
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-drupal/components/footer.js",
"language": "javascript",
"file_size": 1210,
"cut_index": 518,
"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-drupal/components/intro.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
e { NextApiRequest, NextApiResponse } from "next";
import type { Comment } from "../interfaces";
import redis from "./redis";
import clearUrl from "./clearUrl";
export default async function fetchComment(
req: NextApiRequest,
res: NextApiResponse,
) {
const url = clearUrl(req.headers.referer);
if (!redis) {
... | nts = rawComments.map((c) => {
const comment: Comment = JSON.parse(c);
delete comment.user.email;
return comment;
});
return res.status(200).json(comments);
} catch (_) {
return res.status(400).json({ message: "Unexpected e | const comme | {
"filepath": "examples/blog-with-comment/lib/fetchComment.ts",
"language": "typescript",
"file_size": 818,
"cut_index": 522,
"middle_length": 14
} |
;
import { useRouter } from "next/router";
import ErrorPage from "next/error";
import Comment from "../../components/comment";
import Container from "../../components/container";
import distanceToNow from "../../lib/dateRelative";
import { getAllPosts, getPostBySlug } from "../../lib/getPost";
import markdownToHtml fro... | <div>Loading…</div>
) : (
<div>
<article>
<header>
<h1 className="text-4xl font-bold">{post.title}</h1>
{post.excerpt ? (
<p className="mt-2 text-xl">{post.excerpt}</p>
| (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return (
<Container>
<Head>
<title>{post.title} | My awesome blog</title>
</Head>
{router.isFallback ? (
| {
"filepath": "examples/blog-with-comment/pages/posts/[slug].tsx",
"language": "tsx",
"file_size": 2076,
"cut_index": 563,
"middle_length": 229
} |
APHCMS_PROJECT_API, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${
preview
? process.env.GRAPHCMS_DEV_AUTH_TOKEN
: process.env.GRAPHCMS_PROD_AUTH_TOKEN
}`,
},
body: JSON.stringify({
query,
variables,
... | ge) {
slug
}
}`,
{
preview: true,
variables: {
stage: "DRAFT",
slug,
},
},
);
return data.post;
}
export async function getAllPostsWithSlug() {
const data = await fetchAPI(`
{
pos | fetch API");
}
return json.data;
}
export async function getPreviewPostBySlug(slug) {
const data = await fetchAPI(
`
query PostBySlug($slug: String!, $stage: Stage!) {
post(where: {slug: $slug}, stage: $sta | {
"filepath": "examples/cms-graphcms/lib/graphcms.js",
"language": "javascript",
"file_size": 3235,
"cut_index": 614,
"middle_length": 229
} |
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 { getAllPostsForHome } from "../lib/graphcms";
import Head from "next/head";
import { CMS_... | }
coverImage={heroPost.coverImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts.length > | review}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title | {
"filepath": "examples/cms-graphcms/pages/index.js",
"language": "javascript",
"file_size": 1271,
"cut_index": 524,
"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-drupal/components/alert.js",
"language": "javascript",
"file_size": 1203,
"cut_index": 518,
"middle_length": 229
} |
t { withPageAuthRequired } from "@auth0/nextjs-auth0/client";
import Layout from "../components/layout";
import { User } from "../interfaces";
type ProfileCardProps = {
user: User;
};
const ProfileCard = ({ user }: ProfileCardProps) => {
return (
<>
<h1>Profile</h1>
<div>
<h3>Profile (cli... | ading }) => {
return (
<Layout user={user} loading={isLoading}>
{isLoading ? <>Loading...</> : <ProfileCard user={user} />}
</Layout>
);
};
// Protected route, checking user authentication client-side.(CSR)
export default withPageAuthReq | ({ user, isLo | {
"filepath": "examples/auth0/pages/profile.tsx",
"language": "tsx",
"file_size": 803,
"cut_index": 517,
"middle_length": 14
} |
React from "react";
import Link from "next/link";
import { motion } from "framer-motion";
import { images } from "../constants";
const transition = {
duration: 1,
ease: [0.43, 0.13, 0.23, 0.96],
};
const imageVariants = {
exit: { y: "50%", opacity: 0, transition },
enter: {
y: "0%",
opacity: 1,
t... | `}
alt="The Barbican"
/>
<motion.div className="back" variants={backVariants}>
<Link href="/">← Back</Link>
</motion.div>
</motion.div>
<style>
{`
.single {
overflow: hidden;
h | }) => (
<>
<motion.div className="single" initial="exit" animate="enter" exit="exit">
<motion.img
variants={imageVariants}
src={`https://images.unsplash.com/${images[index]}?auto=format&fit=crop&w=1500 | {
"filepath": "examples/with-framer-motion/components/SingleImage.js",
"language": "javascript",
"file_size": 1403,
"cut_index": 524,
"middle_length": 229
} |
ents/date";
import CoverImage from "../components/cover-image";
import PostTitle from "../components/post-title";
import Categories from "../components/categories";
export default function PostHeader({
title,
coverImage,
date,
author,
categories,
}) {
return (
<>
<PostTitle>{title}</PostTitle>
... | xl mx-auto">
<div className="block md:hidden mb-6">
<Avatar author={author} />
</div>
<div className="mb-6 text-lg">
Posted <Date dateString={date} />
{categories?.length ? <Categories categories={categ | Image} />
</div>
<div className="max-w-2 | {
"filepath": "examples/cms-drupal/components/post-header.js",
"language": "javascript",
"file_size": 951,
"cut_index": 582,
"middle_length": 52
} |
orPage from "next/error";
import Head from "next/head";
import {
getPathsFromContext,
getResourceCollectionFromContext,
getResourceFromContext,
} from "next-drupal";
import Container from "../components/container";
import PostBody from "../components/post-body";
import MoreStories from "../components/more-storie... | = useRouter();
if (!router.isFallback && !post?.id) {
return <ErrorPage statusCode={404} />;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
| ents/layout";
import PostTitle from "../components/post-title";
import { CMS_NAME } from "../lib/constants";
import { absoluteURL } from "../lib/api";
export default function Post({ post, morePosts, preview }) {
const router | {
"filepath": "examples/cms-drupal/pages/[...slug].js",
"language": "javascript",
"file_size": 2979,
"cut_index": 563,
"middle_length": 229
} |
t, Search } from "commerce-sdk";
export default async function getProducts(searchQuery) {
const clientConfig = {
headers: {
authorization: ``,
},
parameters: {
clientId: process.env.SFDC_CLIENT_ID,
secret: process.env.SFDC_SECRET,
organizationId: process.env.SFDC_ORGANIZATIONID,
... | Token({
headers,
body: {
grant_type: "client_credentials",
},
});
const configWithAuth = {
...clientConfig,
headers: { authorization: `Bearer ${shopperToken.access_token}` },
};
const searchClient = new Search.ShopperSea | const base64data = Buffer.from(credentials).toString("base64");
const headers = { Authorization: `Basic ${base64data}` };
const client = new Customer.ShopperLogin(clientConfig);
const shopperToken = await client.getAccess | {
"filepath": "examples/with-sfcc/sfcc.js",
"language": "javascript",
"file_size": 1633,
"cut_index": 537,
"middle_length": 229
} |
Image from "next/image";
import Link from "next/link";
import { useState } from "react";
function cn(...classes) {
return classes.filter(Boolean).join(" ");
}
export default function ProductCard({ product }) {
const [isLoading, setLoading] = useState(true);
return (
<Link href={`/products/${product.id}`} ... | e"
: "scale-100 blur-0 grayscale-0",
)}
onLoad={() => setLoading(false)}
/>
</div>
<div className="mt-4 flex items-center justify-between text-base font-medium text-gray-900">
<h3>{product.name} | src={product.imageGroups[0].images[0].link}
fill
className={cn(
"object-cover duration-700 ease-in-out group-hover:opacity-75 ",
isLoading
? "scale-110 blur-2xl grayscal | {
"filepath": "examples/with-sfcc/components/ProductCard.tsx",
"language": "tsx",
"file_size": 1175,
"cut_index": 518,
"middle_length": 229
} |
mage";
import getProducts from "../../sfcc.js";
export default function Product({ product }) {
return (
<div className="flex h-screen flex-col justify-between">
<div className="mx-auto mt-16 max-w-2xl px-4 sm:px-6 lg:max-w-7xl lg:px-8">
<div className="mx-auto flex flex-col sm:flex-row">
... | <h1 className="mt-3 text-4xl font-bold text-gray-500 sm:text-3xl sm:tracking-tight lg:text-3xl">
${product.price}
</h1>
<div className="mt-10 mb-5 border-t border-gray-200 pt-10 font-bold">
Descrip | <div className="mt-10 flex flex-col sm:mt-0 sm:ml-10">
<h1 className="mt-1 text-4xl font-bold uppercase text-gray-900 sm:text-5xl sm:tracking-tight lg:text-5xl">
{product.name}
</h1>
| {
"filepath": "examples/with-sfcc/pages/products/[slug].tsx",
"language": "tsx",
"file_size": 1678,
"cut_index": 537,
"middle_length": 229
} |
GetStaticPaths } from "next";
import { User } from "../../interfaces";
import { sampleUserData } from "../../utils/sample-data";
import Layout from "../../components/Layout";
import ListDetail from "../../components/ListDetail";
type Props = {
item?: User;
errors?: string;
};
const StaticPropsDetail = ({ item, e... | export default StaticPropsDetail;
export const getStaticPaths: GetStaticPaths = async () => {
// Get the paths we want to pre-render based on users
const paths = sampleUserData.map((user) => ({
params: { id: user.id.toString() },
}));
// We'l | </p>
</Layout>
);
}
return (
<Layout
title={`${
item ? item.name : "User Detail"
} | Next.js + TypeScript Example`}
>
{item && <ListDetail item={item} />}
</Layout>
);
};
| {
"filepath": "examples/with-typescript/pages/users/[id].tsx",
"language": "tsx",
"file_size": 1714,
"cut_index": 537,
"middle_length": 229
} |
ePage() {
return (
<>
<Container>
<div className="space-y-6">
<h1 className="text-2xl font-bold">
Hey, I'm a Senior Software Engineer at Company. I enjoy working with
Next.js and crafting beautiful front-end experiences.
</h1>
<p>
Thi... | v>
</Container>
<div className="container max-w-4xl m-auto px-4 mt-20">
<Image
src="/desk.jpg"
alt="my desk"
width={1920 / 2}
height={1280 / 2}
/>
</div>
</>
);
}
export defa | p>Deploy your own in a few minutes.</p>
</di | {
"filepath": "examples/blog-with-comment/pages/index.tsx",
"language": "tsx",
"file_size": 928,
"cut_index": 606,
"middle_length": 52
} |
import Avatar from "../components/avatar";
import Date from "../components/date";
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">
<Cover... | </Link>
</h3>
<div className="mb-4 text-lg">
<Date dateString={date} />
</div>
<p className="mb-4 text-lg leading-relaxed">{excerpt}</p>
<Avatar name={author.name} picture={author.picture.url} />
</div>
);
| {title}
| {
"filepath": "examples/cms-graphcms/components/post-preview.js",
"language": "javascript",
"file_size": 784,
"cut_index": 512,
"middle_length": 14
} |
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:mb-16"... | html: title }}
></Link>
</h3>
<div className="mb-4 md:mb-0 text-lg">
<Date dateString={date} />
</div>
</div>
<div>
<div
className="text-lg leading-relaxed mb-4"
| 8 mb-20 md:mb-28">
<div>
<h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<Link
href={slug}
className="hover:underline"
dangerouslySetInnerHTML={{ __ | {
"filepath": "examples/cms-drupal/components/hero-post.js",
"language": "javascript",
"file_size": 1159,
"cut_index": 518,
"middle_length": 229
} |
ost-preview";
export default function MoreStories({ posts }) {
return (
<section>
<h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
More Stories
</h2>
<div className="grid grid-cols-1 md:grid-cols-2 md:gap-16 lg:gap-32 gap-20 md:gap-32 mb-32">
{... | author={{
name: node.uid.field_name,
avatar: {
url: absoluteURL(node.uid.user_picture.uri.url),
},
}}
slug={node.path.alias}
excerpt={node.body.summary}
| }}
date={node.created}
| {
"filepath": "examples/cms-drupal/components/more-stories.js",
"language": "javascript",
"file_size": 948,
"cut_index": 582,
"middle_length": 52
} |
ad";
import { getResourceCollectionFromContext } from "next-drupal";
import Container 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 { CMS_NA... | coverImage={{
sourceUrl: absoluteURL(heroPost.field_image.uri.url),
}}
date={heroPost.created}
author={{
name: heroPost.uid.field_name,
avatar: {
url: absoluteU | <Layout>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title}
| {
"filepath": "examples/cms-drupal/pages/index.js",
"language": "javascript",
"file_size": 1610,
"cut_index": 537,
"middle_length": 229
} |
Ref } from "react";
import Header from "../components/Header";
import ProductCard from "../components/ProductCard";
import getProducts from "../sfcc.js";
export default function Gallery({ data }) {
let coffeeRef = useRef<HTMLParagraphElement>();
const scrollHandler = (e) => {
e.preventDefault();
// @ts-ig... | d uppercase text-gray-900 sm:text-5xl sm:tracking-tight lg:text-5xl"
ref={coffeeRef}
>
Crafted by us, for you
</p>
</div>
</div>
<div className="grid grid-cols-1 gap-y-10 gap-x-6 | max-w-2xl px-4 sm:px-6 lg:max-w-7xl lg:px-8">
<div className="sm:py-15 mx-auto max-w-7xl py-16 px-4 sm:px-6 lg:px-8">
<div className="text-center">
<p
className="mt-1 text-4xl font-bol | {
"filepath": "examples/with-sfcc/pages/index.tsx",
"language": "tsx",
"file_size": 1408,
"cut_index": 524,
"middle_length": 229
} |
import { User } from "../../interfaces";
import { sampleUserData } from "../../utils/sample-data";
import Layout from "../../components/Layout";
import List from "../../components/List";
type Props = {
items: User[];
};
const WithStaticProps = ({ items }: Props) => (
<Layout title="Users List | Next.js + TypeScri... |
</Layout>
);
export const getStaticProps: GetStaticProps = async () => {
// Example for including static props in a Next.js function component page.
// Don't forget to include the respective types for any props passed into
// the component.
con | <p>
<Link href="/">Go home</Link>
</p> | {
"filepath": "examples/with-typescript/pages/users/index.tsx",
"language": "tsx",
"file_size": 992,
"cut_index": 582,
"middle_length": 52
} |
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-graphcms/components/intro.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
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 "components/section-separator";
im... | n (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback ? (
<PostTitle>Loading…</PostTitle>
) : (
<>
<article>
<Head>
<title>
| rt { CMS_NAME } from "lib/constants";
export default function Post({ post, morePosts, preview }) {
const router = useRouter();
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
retur | {
"filepath": "examples/cms-graphcms/pages/posts/[slug].js",
"language": "javascript",
"file_size": 2116,
"cut_index": 563,
"middle_length": 229
} |
mage";
import img from "../public/hero.jpg";
export default function Header({ scrollHandler }) {
return (
<header className="relative">
<div className="absolute inset-x-0 bottom-0 h-1/2 bg-gray-100" />
<div className="mx-auto">
<div className="relative shadow-xl sm:overflow-hidden">
... | :py-32 lg:px-8">
<p className="relative left-0 right-0 mx-auto mt-5 max-w-xl text-center text-xl font-semibold uppercase tracking-wide text-orange-600">
The Coffee House
</p>
<h1 className="mt-1 text-center | eholder="blur"
alt="Coffee grinder"
/>
<div className="absolute inset-0 bg-orange-100 mix-blend-multiply" />
</div>
<div className="relative px-4 py-16 sm:px-6 sm:py-24 lg | {
"filepath": "examples/with-sfcc/components/Header.tsx",
"language": "tsx",
"file_size": 1766,
"cut_index": 537,
"middle_length": 229
} |
m "../components/avatar";
import Date from "../components/date";
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 title={titl... | Link>
</h3>
<div className="text-lg mb-4">
<Date dateString={date} />
</div>
<div
className="text-lg leading-relaxed mb-4"
dangerouslySetInnerHTML={{ __html: excerpt }}
/>
<Avatar author={author} | gerouslySetInnerHTML={{ __html: title }}
></ | {
"filepath": "examples/cms-drupal/components/post-preview.js",
"language": "javascript",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
act-tsparticles";
const ParticlesComponent = () => {
const particlesInit = async (engine: Engine) => {
// here engine can be used for loading additional presets or plugins
// PRESETS
// https://github.com/matteobruni/tsparticles/tree/main/presets all official tsParticles presets
// for example
//... | al tsParticles additional shapes
// for example
// await loadHeartShape(engine); // it requires "tsparticles-shape-heart" dependency
// INTERACTIONS
// https://github.com/matteobruni/tsparticles/tree/main/interactions all offciail tsParticl | tsParticles plugins
// for example
// await loadInfectionPlugin(engine); // it requires "tsparticles-plugin-infection" dependency
// SHAPES
// https://github.com/matteobruni/tsparticles/tree/main/shapes all offici | {
"filepath": "examples/with-particles/components/particles.tsx",
"language": "tsx",
"file_size": 3491,
"cut_index": 614,
"middle_length": 229
} |
rom "next/head";
import Image from "next/image";
import Particles from "../components/particles";
import styles from "../styles/Home.module.css";
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content... | </p>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>Documentation →</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
| }>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by editing{" "}
<code className={styles.code}>pages/index.tsx</code>
| {
"filepath": "examples/with-particles/pages/index.tsx",
"language": "tsx",
"file_size": 2431,
"cut_index": 563,
"middle_length": 229
} |
// Native
const { join } = require("path");
const { format } = require("url");
// Packages
const { BrowserWindow, app, ipcMain } = require("electron");
const isDev = require("electron-is-dev");
const prepareNext = require("electron-next");
// Prepare the renderer once the app is ready
app.on("ready", async () => {
... | ow.loadURL(url);
});
// Quit the app once all windows are closed
app.on("window-all-closed", app.quit);
// listen the channel `message` and resend the received message to the renderer process
ipcMain.on("message", (event, message) => {
event.sender.sen | preload.js"),
},
});
const url = isDev
? "http://localhost:8000"
: format({
pathname: join(__dirname, "../renderer/out/index.html"),
protocol: "file:",
slashes: true,
});
mainWind | {
"filepath": "examples/with-electron/main/index.js",
"language": "javascript",
"file_size": 1024,
"cut_index": 512,
"middle_length": 229
} |
const resp = await fetch("/api/todos");
const data = await resp.json();
setTodos(data);
}
loadTodos();
}, []);
return (
<div className="container">
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1... | </p>
);
})}
<p className="description">
Get started by editing <code>pages/index.js</code>
</p>
<div className="grid">
<a href="https://nextjs.org/docs" className="card">
<h3>D | s-loading">Todos loading...</p>}
{todos &&
todos.map((todo) => {
return (
<p className="todos-item" key={todo.id}>
{todo.text} {todo.done && "(complete)"}
| {
"filepath": "examples/with-knex/pages/index.js",
"language": "javascript",
"file_size": 6295,
"cut_index": 716,
"middle_length": 229
} |
dler");
const createRedisHandler = require("@neshca/cache-handler/redis-stack").default;
const createLruHandler = require("@neshca/cache-handler/local-lru").default;
const { createClient } = require("redis");
const { PHASE_PRODUCTION_BUILD } = require("next/constants");
/* from https://caching-tools.github.io/next-sha... | // Redis won't work without error handling.
// NB do not throw exceptions in the redis error listener,
// because it will prevent reconnection after a socket exception.
client.on("error", (e) => {
if (typeof process.env.NEXT_PRIV | omment-1919145094
if (PHASE_PRODUCTION_BUILD !== process.env.NEXT_PHASE) {
try {
// Create a Redis client.
client = createClient({
url: process.env.REDIS_URL ?? "redis://localhost:6379",
});
| {
"filepath": "examples/cache-handler-redis/cache-handler.js",
"language": "javascript",
"file_size": 2784,
"cut_index": 563,
"middle_length": 229
} |
"next/navigation";
import { CacheStateWatcher } from "../cache-state-watcher";
import { Suspense } from "react";
import { RevalidateFrom } from "../revalidate-from";
import Link from "next/link";
type TimeData = {
unixtime: number;
datetime: string;
timezone: string;
};
const timeZones = ["cet", "gmt"];
export... |
return (
<>
<header className="header">
{timeZones.map((timeZone) => (
<Link key={timeZone} className="link" href={`/${timeZone}`}>
{timeZone.toUpperCase()} Time
</Link>
))}
</header>
|
const data = await fetch(
`https://worldtimeapi.org/api/timezone/${timezone}`,
{
next: { tags: ["time-data"] },
},
);
if (!data.ok) {
notFound();
}
const timeData: TimeData = await data.json();
| {
"filepath": "examples/cache-handler-redis/app/[timezone]/page.tsx",
"language": "tsx",
"file_size": 1681,
"cut_index": 537,
"middle_length": 229
} |
useState("");
const [message, setMessage] = useState(null);
useEffect(() => {
const handleMessage = (event, message) => setMessage(message);
window.electron.message.on(handleMessage);
return () => {
window.electron.message.off(handleMessage);
};
}, []);
const handleSubmit = (event) => ... | type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
/>
</form>
<style jsx>{`
h1 {
color: red;
font-size: 50px;
}
`}</style>
</div>
);
};
expor | <form onSubmit={handleSubmit}>
<input
| {
"filepath": "examples/with-electron/renderer/pages/index.js",
"language": "javascript",
"file_size": 930,
"cut_index": 606,
"middle_length": 52
} |
styled from "styled-components";
const Container = styled.div`
padding: 0 0.5rem;
display: flex;
flex-flow: column nowrap;
justify-content: center;
align-items: center;
height: 100vh;
min-height: 100vh;
`;
const Main = styled.main`
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;... | 1.5;
font-size: 1.5rem;
`;
const CodeTag = styled.code`
background: #fafafa;
border-radius: 5px;
margin: 0 0.75rem;
padding: 0.75rem;
font-size: 1.1rem;
font-family:
Menlo,
Monaco,
Lucida Console,
Liberation Mono,
DejaVu S | olor: ${({ theme }) => theme.colors.secondary};
text-decoration: none;
&:hover,
:focus,
:active {
text-decoration: underline;
}
}
`;
const Description = styled.p`
text-align: center;
line-height: | {
"filepath": "examples/with-styled-components/app/_components/sharedstyles.tsx",
"language": "tsx",
"file_size": 1136,
"cut_index": 518,
"middle_length": 229
} |
use client";
import { ReactNode, useEffect, useState } from "react";
type CacheStateWatcherProps = { time: number; revalidateAfter: number };
export function CacheStateWatcher({
time,
revalidateAfter,
}: CacheStateWatcherProps): ReactNode {
const [cacheState, setCacheState] = useState("");
const [countDown, ... | uestAnimationFrame(check);
return () => {
cancelAnimationFrame(id);
};
}, [revalidateAfter, time]);
return (
<>
<div className={`cache-state ${cacheState}`}>
Cache state: {cacheState}
</div>
<div className= | - now) / 1000).toFixed(3),
);
if (now > time + revalidateAfter) {
setCacheState("stale");
return;
}
setCacheState("fresh");
id = requestAnimationFrame(check);
}
id = req | {
"filepath": "examples/cache-handler-redis/app/cache-state-watcher.tsx",
"language": "tsx",
"file_size": 1055,
"cut_index": 513,
"middle_length": 229
} |
tp";
import { useMemo } from "react";
import {
ApolloClient,
InMemoryCache,
NormalizedCacheObject,
} from "@apollo/client";
import resolvers from "./resolvers";
import typeDefs from "./schema";
let apolloClient: ApolloClient<NormalizedCacheObject> | undefined;
export type ResolverContext = {
req?: IncomingMes... | st { HttpLink } = require("@apollo/client");
return new HttpLink({
uri: "/api/graphql",
credentials: "same-origin",
});
}
}
function createApolloClient(context?: ResolverContext) {
return new ApolloClient({
ssrMode: typeof wind | hema");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
return new SchemaLink({ schema, context });
} else {
con | {
"filepath": "examples/with-typescript-graphql/lib/apollo.ts",
"language": "typescript",
"file_size": 2048,
"cut_index": 563,
"middle_length": 229
} |
Effect } from "react";
import Script from "next/script";
import { useRouter } from "next/router";
import * as fbq from "../lib/fpixel";
function MyApp({ Component, pageProps }) {
const router = useRouter();
useEffect(() => {
// This pageview only triggers the first time (it's important for Pixel to have real ... | tive"
dangerouslySetInnerHTML={{
__html: `
!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._ | outer.events.off("routeChangeComplete", handleRouteChange);
};
}, [router.events]);
return (
<>
{/* Global Site Code Pixel - Facebook Pixel */}
<Script
id="fb-pixel"
strategy="afterInterac | {
"filepath": "examples/with-facebook-pixel/_pages/_app.js",
"language": "javascript",
"file_size": 1446,
"cut_index": 524,
"middle_length": 229
} |
led from "styled-components";
import Link from "next/link";
const FlexContainer = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-flow: column wrap;
max-width: 800px;
margin-top: 3rem;
`;
const Card = styled.div`
padding: 1.5rem;
color: inherit;
text-decoration: none;
... | f3;
}
`;
const StyledLink = styled(Link)`
margin: 0 0 1rem 0;
font-size: 1.5rem;
`;
export default function Cards() {
return (
<FlexContainer>
<Card>
<StyledLink href="/about">About Page →</StyledLink>
</Card>
</F | r-color: #0070 | {
"filepath": "examples/with-styled-components/app/_components/cards.tsx",
"language": "tsx",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
orPage from "next/error";
import { getImageUrl } from "takeshape-routing";
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 "../../component... | post, morePosts, preview }) {
const router = useRouter();
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return (
<Layout preview={preview}>
<Container>
<Header />
{router.isFallback | /lib/api";
import PostTitle from "../../components/post-title";
import Head from "next/head";
import { CMS_NAME } from "../../lib/constants";
import markdownToHtml from "../../lib/markdownToHtml";
export default function Post({ | {
"filepath": "examples/cms-takeshape/pages/posts/[slug].js",
"language": "javascript",
"file_size": 2631,
"cut_index": 563,
"middle_length": 229
} |
se } from "react";
import Link from "next/link";
interface Post {
id: number;
title: string;
content?: string;
createdAt: string;
author?: {
name: string;
};
}
// Disable static generation
export const dynamic = "force-dynamic";
function PostsList() {
const searchParams = useSearchParams();
const... | ch posts");
}
const data = await res.json();
setPosts(data.posts);
setTotalPages(data.totalPages);
} catch (error) {
console.error("Error fetching posts:", error);
} finally {
setIsLoading(false); | State(true);
useEffect(() => {
async function fetchPosts() {
setIsLoading(true);
try {
const res = await fetch(`/api/posts?page=${page}`);
if (!res.ok) {
throw new Error("Failed to fet | {
"filepath": "examples/prisma-postgres/app/posts/page.tsx",
"language": "tsx",
"file_size": 3768,
"cut_index": 614,
"middle_length": 229
} |
sable */
import * as types from "./graphql";
import { TypedDocumentNode as DocumentNode } from "@graphql-typed-document-node/core";
const documents = {
"\n mutation UpdateName($name: String!) {\n updateName(name: $name) {\n id\n name\n status\n }\n }\n":
types.UpdateNameDocument,
"\n qu... | port function graphql(
source: "\n query Viewer {\n viewer {\n id\n name\n status\n }\n }\n",
): (typeof documents)["\n query Viewer {\n viewer {\n id\n name\n status\n }\n }\n"];
export function graphql(sou | updateName(name: $name) {\n id\n name\n status\n }\n }\n",
): (typeof documents)["\n mutation UpdateName($name: String!) {\n updateName(name: $name) {\n id\n name\n status\n }\n }\n"];
ex | {
"filepath": "examples/with-typescript-graphql/lib/gql/gql.ts",
"language": "typescript",
"file_size": 1265,
"cut_index": 524,
"middle_length": 229
} |
nt";
import { graphql } from "lib/gql";
import Link from "next/link";
import { useState } from "react";
import { initializeApollo } from "../lib/apollo";
const updateNameDocument = graphql(/* GraphQL */ `
mutation UpdateName($name: String!) {
updateName(name: $name) {
id
name
status
}
}
`... | / Follow apollo suggestion to update cache
// https://www.apollographql.com/docs/angular/features/cache-updates/#update
update: (cache, mutationResult) => {
const { data } = mutationResult;
if (!data) return; // Cancel updating | t);
const [newName, setNewName] = useState("");
const [updateNameMutation] = useMutation(updateNameDocument);
const onChangeName = () => {
updateNameMutation({
variables: {
name: newName,
},
/ | {
"filepath": "examples/with-typescript-graphql/pages/index.tsx",
"language": "tsx",
"file_size": 2356,
"cut_index": 563,
"middle_length": 229
} |
e as DocumentNode } from "@graphql-typed-document-node/core";
export type FragmentType<TDocumentType extends DocumentNode<any, any>> =
TDocumentType extends DocumentNode<infer TType, any>
? TType extends { " $fragmentName"?: infer TKey }
? TKey extends string
? { " $fragmentRefs"?: { [key in TKey]:... | tNode<TType, any>> | null | undefined,
): TType | null | undefined;
// return array of non-nullable if `fragmentType` is array of non-nullable
export function useFragment<TType>(
_documentNode: DocumentNode<TType, any>,
fragmentType: ReadonlyArray<Frag | fragmentType: FragmentType<DocumentNode<TType, any>>,
): TType;
// return nullable if `fragmentType` is nullable
export function useFragment<TType>(
_documentNode: DocumentNode<TType, any>,
fragmentType: FragmentType<Documen | {
"filepath": "examples/with-grafbase/gql/fragment-masking.ts",
"language": "typescript",
"file_size": 1691,
"cut_index": 537,
"middle_length": 229
} |
rt * as types from "./graphql";
import { TypedDocumentNode as DocumentNode } from "@graphql-typed-document-node/core";
const documents = {
"\n query GetAllPosts($first: Int!) {\n postCollection(first: $first) {\n edges {\n node {\n id\n title\n slug\n }\n }\n ... | }\n }\n",
): (typeof documents)["\n query GetAllPosts($first: Int!) {\n postCollection(first: $first) {\n edges {\n node {\n id\n title\n slug\n }\n }\n }\n }\n"];
export function graphql(
sou | lugDocument,
};
export function graphql(
source: "\n query GetAllPosts($first: Int!) {\n postCollection(first: $first) {\n edges {\n node {\n id\n title\n slug\n }\n }\n | {
"filepath": "examples/with-grafbase/gql/gql.ts",
"language": "typescript",
"file_size": 1588,
"cut_index": 537,
"middle_length": 229
} |
";
import { graphql } from "../gql";
import { grafbase } from "../lib/grafbase";
import type { Metadata } from "next";
export const revalidate = 0;
export const metadata: Metadata = {
title: "Grafbase + Next.js",
description: "Grafbase + Next.js",
};
const GetAllPostsDocument = graphql(/* GraphQL */ `
query Ge... | sName="flex">
<nav className="w-[350px] flex flex-col justify-between h-screen overflow-y-auto bg-gray-100">
<ul className="p-8 space-y-2">
<li className="mb-6">
<Link
href="/"
| ction RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const { postCollection } = await grafbase.request(GetAllPostsDocument, {
first: 50,
});
return (
<html lang="en">
<body>
<div clas | {
"filepath": "examples/with-grafbase/app/layout.tsx",
"language": "tsx",
"file_size": 2442,
"cut_index": 563,
"middle_length": 229
} |
ort { Prisma } from "../lib/generated/prisma/client";
export const categories = [
{
name: "Hats",
description: "Things you can wear on your head",
},
{
name: "Socks",
description: "Things you can wear on your feet",
},
{
name: "Shirts",
description: "Things you wear on the top half of... | name: "Socks",
description: "Cool socks that you can wear on your feet",
price: new Prisma.Decimal(12.95),
image: "/images/socks.jpg",
categoryId: 2,
},
{
name: "Sweatshirt",
description: "Cool sweatshirt that you can wear on | elmet.jpg",
categoryId: 1,
},
{
name: "Grey T-Shirt",
description: "A nice shirt that you can wear on your body",
price: new Prisma.Decimal(22.95),
image: "/images/shirt.jpg",
categoryId: 3,
},
{
| {
"filepath": "examples/with-mysql/prisma/data.ts",
"language": "typescript",
"file_size": 1115,
"cut_index": 515,
"middle_length": 229
} |
eact from "react";
import { useServerInsertedHTML } from "next/navigation";
import { StyleProvider, createCache, extractStyle } from "@ant-design/cssinjs";
import type Entity from "@ant-design/cssinjs/es/Cache";
const StyledComponentsRegistry = ({ children }: React.PropsWithChildren) => {
const cache = React.useMemo... | true;
return (
<style
id="antd"
dangerouslySetInnerHTML={{ __html: extractStyle(cache, true) }}
/>
);
});
return <StyleProvider cache={cache}>{children}</StyleProvider>;
};
export default StyledComponentsRegistry;
| {
return;
}
isServerInserted.current = | {
"filepath": "examples/with-ant-design/app/AntdRegistry.tsx",
"language": "tsx",
"file_size": 843,
"cut_index": 535,
"middle_length": 52
} |
from "next/app";
import Head from "next/head";
import "../styles/root.css";
const metas = {
title: "Next.js with-xata",
description: "Run Next.js with Xata with this awesome template",
image:
process.env.NODE_ENV === "development"
? "http://localhost:3000/og.jpg"
: "https://nextjs-with-xata.verce... | />
<meta
property="og:description"
content={metas.description}
key="og:description"
/>
<meta property="og:type" content="website" />
<meta property="twitter:card" content="summary_large_image" | nt={metas.title} key="og:title" />
<meta property="og:image" content={metas.image} key="og:image" />
<meta
property="description"
content={metas.description}
key="description"
| {
"filepath": "examples/with-xata/pages/_app.tsx",
"language": "tsx",
"file_size": 1726,
"cut_index": 537,
"middle_length": 229
} |
ore";
export type Maybe<T> = T | null;
export type InputMaybe<T> = Maybe<T>;
export type Exact<T extends { [key: string]: unknown }> = {
[K in 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,... | viewer: User;
};
export type User = {
__typename?: "User";
id: Scalars["ID"];
name: Scalars["String"];
status: Scalars["String"];
};
export type UpdateNameMutationVariables = Exact<{
name: Scalars["String"];
}>;
export type UpdateNameMutation | Int: number;
Float: number;
};
export type Mutation = {
__typename?: "Mutation";
updateName: User;
};
export type MutationUpdateNameArgs = {
name: Scalars["String"];
};
export type Query = {
__typename?: "Query";
| {
"filepath": "examples/with-typescript-graphql/lib/gql/graphql.ts",
"language": "typescript",
"file_size": 3721,
"cut_index": 614,
"middle_length": 229
} |
e as DocumentNode } from "@graphql-typed-document-node/core";
export type FragmentType<TDocumentType extends DocumentNode<any, any>> =
TDocumentType extends DocumentNode<infer TType, any>
? TType extends { " $fragmentName"?: infer TKey }
? TKey extends string
? { " $fragmentRefs"?: { [key in TKey]:... | tNode<TType, any>> | null | undefined,
): TType | null | undefined;
// return array of non-nullable if `fragmentType` is array of non-nullable
export function useFragment<TType>(
_documentNode: DocumentNode<TType, any>,
fragmentType: ReadonlyArray<Frag | fragmentType: FragmentType<DocumentNode<TType, any>>,
): TType;
// return nullable if `fragmentType` is nullable
export function useFragment<TType>(
_documentNode: DocumentNode<TType, any>,
fragmentType: FragmentType<Documen | {
"filepath": "examples/with-typescript-graphql/lib/gql/fragment-masking.ts",
"language": "typescript",
"file_size": 1691,
"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-takeshape/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
{process.env.TAKESHAPE_PROJECT_ID}/graphql`;
const API_KEY = process.env.TAKESHAPE_API_KEY;
async function fetchAPI(query, { variables } = {}) {
const res = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${API_KEY}`,
},
body: J... | false) {
items {
slug
}
}
}`,
{
variables: {
slug,
},
},
);
return (data?.post?.items || [])[0];
}
export async function getAllPostsWithSlug() {
const data = await fetchAPI(`
{
| }
return json.data;
}
export async function getPreviewPostBySlug(slug) {
const data = await fetchAPI(
`
query PostBySlug($slug: String) {
post: getPostList(filter: {term: {slug: $slug}}, size: 1, onlyEnabled: | {
"filepath": "examples/cms-takeshape/lib/api.js",
"language": "javascript",
"file_size": 2929,
"cut_index": 563,
"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:... | d:mb-0 text-lg">
<Date dateString={date} />
</div>
</div>
<div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
<Avatar name={author.name} picture={author.picture} />
</div>
|
<h3 className="mb-4 text-4xl lg:text-6xl leading-tight">
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 m | {
"filepath": "examples/cms-takeshape/components/hero-post.js",
"language": "javascript",
"file_size": 1026,
"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-takeshape/components/meta.js",
"language": "javascript",
"file_size": 1255,
"cut_index": 524,
"middle_length": 229
} |
import Avatar from "../components/avatar";
import Date from "../components/date";
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">
<Cover... |
</Link>
</h3>
<div className="text-lg mb-4">
<Date dateString={date} />
</div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
<Avatar name={author.name} picture={author.picture} />
</div>
);
} | {title} | {
"filepath": "examples/cms-takeshape/components/post-preview.js",
"language": "javascript",
"file_size": 783,
"cut_index": 512,
"middle_length": 14
} |
async function preview(req, res) {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
if (
req.query.secret !== process.env.TAKESHAPE_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
}
// Fetc... | e: "Invalid slug" });
}
// Enable Draft 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 redirect vulnerabilities
re | f (!post) {
return res.status(401).json({ messag | {
"filepath": "examples/cms-takeshape/pages/api/preview.js",
"language": "javascript",
"file_size": 960,
"cut_index": 582,
"middle_length": 52
} |
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: string;
String: string;
Boolean: boolean;
Int: number;
Float: number;
/**
* A date-time string at UTC, such as 2007-12-03T10:15:30Z, is compliant wi... | . All other input values raise a query error indicating an incorrect type.
*
* # Result Coercion
*
* Where an RFC 3339 compliant date-time string has a time-zone other than UTC, it is shifted to UTC.
* For example, the date-time string 2016- | is a description of an exact instant on the timeline such as the instant that a user account was created.
*
* # Input Coercion
*
* When expected as an input type, only RFC 3339 compliant date-time strings are accepted | {
"filepath": "examples/with-grafbase/gql/graphql.ts",
"language": "typescript",
"file_size": 12722,
"cut_index": 921,
"middle_length": 229
} |
nv/config";
import { PrismaPlanetScale } from "@prisma/adapter-planetscale";
import { PrismaClient } from "../lib/generated/prisma/client";
import { fetch as undiciFetch } from "undici";
import { categories, products } from "./data";
const adapter = new PrismaPlanetScale({
url: process.env.DATABASE_URL,
fetch: und... | );
await prisma.$executeRaw`ALTER TABLE Category AUTO_INCREMENT = 1`;
console.log("Reset category auto increment to 1");
await prisma.category.createMany({
data: categories,
});
console.log("Added category data");
await prisma.product.cr | in product table");
await prisma.category.deleteMany();
console.log("Deleted records in category table");
await prisma.$executeRaw`ALTER TABLE Product AUTO_INCREMENT = 1`;
console.log("Reset product auto increment to 1" | {
"filepath": "examples/with-mysql/prisma/seed.ts",
"language": "typescript",
"file_size": 1294,
"cut_index": 524,
"middle_length": 229
} |
ext";
import Image from "next/image";
import { getXataClient } from "../utils/xata.codegen";
import xatafly from "../public/xatafly.gif";
const pushDummyData = async () => {
const response = await fetch("/api/write-links-to-xata");
if (response.ok) {
window?.location.reload();
}
};
const removeDummyItem = ... | ge src={xatafly} alt={"Xata"} priority />
<h1>
Next.js with<span aria-hidden>‑</span>xata
</h1>
</header>
<article>
{links.length ? (
<ul>
{links.map(({ id, title, url, description } | }),
});
if (status === 200) {
window?.location.reload();
}
};
export default function IndexPage({
links,
}: InferGetServerSidePropsType<typeof getServerSideProps>) {
return (
<main>
<header>
<Ima | {
"filepath": "examples/with-xata/pages/index.tsx",
"language": "tsx",
"file_size": 2522,
"cut_index": 563,
"middle_length": 229
} |
import type { NextApiRequest, NextApiResponse } from "next";
import { getXataClient } from "../../utils/xata.codegen";
const LINKS = [
{
description: "Everything you need to know about Xata APIs and tools.",
title: "Xata Docs",
url: "https://xata.io/docs",
},
{
description: "In case you need to c... | ,
url: "https://xata.io/discord",
},
];
const xata = getXataClient();
export default async function writeLinksToXata(
_req: NextApiRequest,
res: NextApiResponse,
) {
await xata.db.nextjs_with_xata_example.create(LINKS);
res.json({
ok: t | eaving VS Code.",
title: "Xata VS Code Extension",
url: "https://marketplace.visualstudio.com/items?itemName=xata.xata",
},
{
description: "Get help. Offer help. Show us what you built!",
title: "Xata Discord" | {
"filepath": "examples/with-xata/pages/api/write-links-to-xata.ts",
"language": "typescript",
"file_size": 1010,
"cut_index": 512,
"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-takeshape/components/footer.js",
"language": "javascript",
"file_size": 1210,
"cut_index": 518,
"middle_length": 229
} |
components/avatar";
import Date from "../components/date";
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="hidden ... | 2xl mx-auto">
<div className="block md:hidden mb-6">
<Avatar name={author.name} picture={author.picture} />
</div>
<div className="mb-6 text-lg">
<Date dateString={date} />
</div>
</div>
</>
) | rImage} />
</div>
<div className="max-w- | {
"filepath": "examples/cms-takeshape/components/post-header.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
nk from "next/link";
import { SmileFilled } from "@ant-design/icons";
import {
Button,
DatePicker,
Form,
InputNumber,
Select,
Slider,
Switch,
ConfigProvider,
} from "antd";
import theme from "./themeConfig";
const HomePage = () => (
<ConfigProvider theme={theme}>
<div style={{ padding: 100, heigh... | <Form.Item label="Input Number">
<InputNumber
min={1}
max={10}
style={{ width: 100 }}
defaultValue={3}
name="inputNumber"
/>
</Form.Item>
| b-0 mt-3 text-disabled">Welcome to the world !</p>
</div>
<div>
<Form
layout="horizontal"
size={"large"}
labelCol={{ span: 8 }}
wrapperCol={{ span: 8 }}
>
| {
"filepath": "examples/with-ant-design/app/page.tsx",
"language": "tsx",
"file_size": 2177,
"cut_index": 563,
"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-succe | href="/api/exit-preview"
className="underline hover:text-cyan duration-200 transition-colors"
>
Click here
</a>{" "}
to exit preview mode.
| {
"filepath": "examples/cms-takeshape/components/alert.js",
"language": "javascript",
"file_size": 1206,
"cut_index": 518,
"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-takeshape/components/intro.js",
"language": "javascript",
"file_size": 847,
"cut_index": 535,
"middle_length": 52
} |
;
export const MAX_AGE = 60 * 60 * 8; // 8 hours
export function setTokenCookie(res, token) {
const cookie = serialize(TOKEN_NAME, token, {
maxAge: MAX_AGE,
expires: new Date(Date.now() + MAX_AGE * 1000),
httpOnly: true,
secure: process.env.NODE_ENV === "production",
path: "/",
sameSite: "la... | ies(req) {
// For API Routes we don't need to parse the cookies.
if (req.cookies) return req.cookies;
// For pages we do need to parse the cookies.
const cookie = req.headers?.cookie;
return parse(cookie || "");
}
export function getTokenCookie | ("Set-Cookie", cookie);
}
export function parseCook | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/lib/auth-cookies.ts",
"language": "typescript",
"file_size": 967,
"cut_index": 582,
"middle_length": 52
} |
"@hapi/iron";
import { MAX_AGE, setTokenCookie, getTokenCookie } from "./auth-cookies";
const TOKEN_SECRET = process.env.TOKEN_SECRET;
export async function setLoginSession(res, session) {
const createdAt = Date.now();
// Create a session object with a max age that we can validate later
const obj = { ...session... | st session = await Iron.unseal(token, TOKEN_SECRET, Iron.defaults);
const expiresAt = session.createdAt + session.maxAge * 1000;
// Validate the expiration date of the session
if (Date.now() > expiresAt) {
throw new Error("Session expired");
} | = getTokenCookie(req);
if (!token) return;
con | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/lib/auth.ts",
"language": "typescript",
"file_size": 859,
"cut_index": 529,
"middle_length": 52
} |
"react";
import { useRouter } from "next/router";
import Link from "next/link";
import { gql } from "@apollo/client";
import { useMutation, useApolloClient } from "@apollo/client";
import { getErrorMessage } from "../lib/form";
import Field from "../components/field";
const SignInMutation = gql`
mutation SignInMutat... | emailElement = event.currentTarget.elements.email;
const passwordElement = event.currentTarget.elements.password;
try {
await client.resetStore();
const { data } = await signIn({
variables: {
email: emailElement.valu | lient = useApolloClient();
const [signIn] = useMutation(SignInMutation);
const [errorMsg, setErrorMsg] = useState();
const router = useRouter();
async function handleSubmit(event) {
event.preventDefault();
const | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/pages/signin.tsx",
"language": "tsx",
"file_size": 1809,
"cut_index": 537,
"middle_length": 229
} |
react";
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
import { SchemaLink } from "@apollo/client/link/schema";
import { schema } from "../apollo/schema";
import merge from "deepmerge";
let apolloClient;
function createIsomorphLink() {
if (typeof window === "undefined") {
return new Sch... | ient();
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.e | {
ssrMode: typeof window === "undefined",
link: createIsomorphLink(),
cache: new InMemoryCache(),
});
}
export function initializeApollo(initialState = null) {
const _apolloClient = apolloClient ?? createApolloCl | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/apollo/client.tsx",
"language": "tsx",
"file_size": 1645,
"cut_index": 537,
"middle_length": 229
} |
Card";
export default function Home() {
const destinations = new Array(8).fill({
imageSrc: "/img/cat.jpg",
title: "Madison, WI",
subtitle: "Destination",
content:
"Keep close to Nature's heart... and break clear away, once in awhile, and climb a mountain or spend a week in the woods. Wash your ... | mageSrc}
title={destination.title}
subtitle={destination.subtitle}
content={destination.content}
/>
</ion-col>
))}
</ion-row>
</ion-grid>
</IonicLayout>
| ardComponent
imageSrc={destination.i | {
"filepath": "examples/with-ionic/app/page.tsx",
"language": "tsx",
"file_size": 920,
"cut_index": 606,
"middle_length": 52
} |
om "react";
import VideosListResponse from "@api.video/nodejs-client/lib/model/VideosListResponse";
export default function Videos() {
const [videosResponse, setVideosResponse] = useState<
VideosListResponse | undefined
>(undefined);
const [error, setError] = useState<boolean>(false);
useEffect(() => {
... | />
<link rel="icon" href="/favicon.ico" />
</Head>
<header>
<span>api.video videos list</span> 📚
</header>
<main>
<div className="texts-container">
<p>
Welcome to this basic example | }, []);
return (
<div className="global-container">
<Head>
<title>Videos List</title>
<meta
name="description"
content="Generated by create next app & created by api.video"
| {
"filepath": "examples/with-apivideo/pages/videos/index.tsx",
"language": "tsx",
"file_size": 3262,
"cut_index": 614,
"middle_length": 229
} |
eoUploadResponse } from "@api.video/video-uploader";
import Status from "../../components/Status";
import { useRouter } from "next/router";
export default function Uploader() {
const [uploadToken, setUploadToken] = useState<{ token: string } | undefined>(
undefined,
);
const [uploadProgress, setUploadProgres... | ())
.then((res) => setUploadToken(res));
}, []);
const handleSelectFile = async (
e: ChangeEvent<HTMLInputElement>,
): Promise<void> => {
e.preventDefault();
if (!uploadToken || !uploadToken.token) return;
const clearState = () | false);
const [playable, setPlayable] = useState<boolean>(false);
const inputRef = useRef<HTMLInputElement>(null);
const router = useRouter();
useEffect(() => {
fetch("/api/uploadToken")
.then((res) => res.json | {
"filepath": "examples/with-apivideo/pages/uploader/index.tsx",
"language": "tsx",
"file_size": 5752,
"cut_index": 716,
"middle_length": 229
} |
ding, Text, Link, Flex, Box } from "rebass";
function HomePage() {
return (
<Box
sx={{
maxWidth: 1100,
mx: "auto",
px: 3,
textAlign: "center",
}}
>
<Heading
as="h1"
children="Next.js + Rebass"
mb={3}
fontSize={[4, 5, 6]}
... | <Link
variant="nav"
href="http://jxnblk.com/rebass/"
sx={{
fontWeight: "600",
color: "white",
textDecoration: "none",
}}
>
REBASS
</ | ext.js/"
sx={{
fontWeight: "600",
color: "white",
textDecoration: "none",
}}
>
Next.js
</Link>
<Box mx="auto" />
| {
"filepath": "examples/with-rebass/pages/index.js",
"language": "javascript",
"file_size": 1467,
"cut_index": 524,
"middle_length": 229
} |
orce-dynamic"; // This disables SSG and ISR
import prisma from "@/lib/prisma";
import Link from "next/link";
export default async function Home() {
const posts = await prisma.post.findMany({
orderBy: {
createdAt: "desc",
},
take: 6,
include: {
author: {
select: {
name: ... | className="group">
<div className="border rounded-lg shadow-md bg-white p-6 hover:shadow-lg transition-shadow duration-300">
<h2 className="text-2xl font-semibold text-blue-600 group-hover:underline mb-2">
{post.ti | ld mb-12 text-[#333333]">
Recent Posts
</h1>
<div className="grid gap-8 md:grid-cols-2 lg:grid-cols-3 w-full max-w-6xl">
{posts.map((post) => (
<Link key={post.id} href={`/posts/${post.id}`} | {
"filepath": "examples/prisma-postgres/app/page.tsx",
"language": "tsx",
"file_size": 1870,
"cut_index": 537,
"middle_length": 229
} |
md border border-gray-300 overflow-y-auto h-[90vh]">
<div className="max-w-3xl bg-white p-8 rounded-lg shadow-md border border-gray-300">
<h1 className="text-3xl font-bold text-gray-900 mb-6">
🛠️ Prisma Postgres Setup Guide
</h1>
<p className="text-gray-700">
... | e
</h2>
<p className="text-gray-700 mt-2">
Create a new Prisma Postgres database instance:
</p>
<ol className="list-decimal pl-6 mt-2 space-y-1 text-gray-700">
<li>
| , you need to connect it to a database.
</p>
{/* Step 1 */}
<div className="mt-6">
<h2 className="text-2xl font-semibold text-gray-900">
1. Create a Prisma Postgres instanc | {
"filepath": "examples/prisma-postgres/app/setup/page.tsx",
"language": "tsx",
"file_size": 7903,
"cut_index": 716,
"middle_length": 229
} |
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 { getAllPostsForHome } from "../lib/api";
import Head from "next/head";
import { CMS_NAME ... | itle}
coverImage={heroPost.coverImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts.leng | w={preview}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.t | {
"filepath": "examples/cms-takeshape/pages/index.js",
"language": "javascript",
"file_size": 1273,
"cut_index": 524,
"middle_length": 229
} |
o from "crypto";
/**
* User methods. The example doesn't contain a DB, but for real applications you must use a
* db here, such as MongoDB, Fauna, SQL, etc.
*/
const users = [];
export async function createUser({ email, password }) {
// Here you should create the user and save the salt and hashed password (some... | ata persistence without a proper DB
users.push(user);
return user;
}
// Here you should lookup for the user in your DB
export async function findUser({ email }) {
// This is an in memory store for users, there is no data persistence without a prope | Sync(password, salt, 1000, 64, "sha512")
.toString("hex");
const user = {
id: crypto.randomUUID(),
createdAt: Date.now(),
email,
hash,
salt,
};
// This is an in memory store for users, there is no d | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/lib/user.ts",
"language": "typescript",
"file_size": 1440,
"cut_index": 524,
"middle_length": 229
} |
"react";
import { useRouter } from "next/router";
import Link from "next/link";
import { gql, useMutation } from "@apollo/client";
import { getErrorMessage } from "../lib/form";
import Field from "../components/field";
const SignUpMutation = gql`
mutation SignUpMutation($email: String!, $password: String!) {
sig... | urrentTarget.elements.password;
try {
await signUp({
variables: {
email: emailElement.value,
password: passwordElement.value,
},
});
router.push("/signin");
} catch (error) {
setErrorMsg | rorMsg, setErrorMsg] = useState();
const router = useRouter();
async function handleSubmit(event) {
event.preventDefault();
const emailElement = event.currentTarget.elements.email;
const passwordElement = event.c | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/pages/signup.tsx",
"language": "tsx",
"file_size": 1633,
"cut_index": 537,
"middle_length": 229
} |
lt function Home() {
return (
<div className="global-container">
<Head>
<title>api.video sample app</title>
<meta
name="description"
content="Generated by create next app & created by api.video"
/>
<link rel="icon" href="/favicon.ico" />
</Head>
... | features examples such as <a href="/uploader">video uploader</a>,{" "}
<a href="/videos">videos list</a> and player components.
</p>
<p>
api.video provides APIs and clients to handle all your video needs | this basic sample app, you will find{" "}
<a
href="https://api.video"
target="_blank"
rel="noopener noreferrer"
>
api.video
</a>{" "}
| {
"filepath": "examples/with-apivideo/pages/index.tsx",
"language": "tsx",
"file_size": 3111,
"cut_index": 614,
"middle_length": 229
} |
next/image";
import { useRouter } from "next/router";
import React, { ChangeEvent, useState } from "react";
import ApiVideoPlayer, { PlayerTheme } from "@api.video/react-player";
interface IVideoViewProps {
children: React.ReactNode;
videoId: string;
uploaded: string;
}
const VideoView: NextPage<IVideoViewProps>... | ]: e.currentTarget.value,
});
return (
<div className="global-container">
<Head>
<title>Video view</title>
<meta
name="description"
content="Generated by create next app & created by api.video"
/ | t [hideControls, setHideControls] = useState<boolean>(false);
const router = useRouter();
const handleChangeSetting = (e: ChangeEvent<HTMLInputElement>) =>
setPlayerTheme({
...playerTheme,
[e.currentTarget.id | {
"filepath": "examples/with-apivideo/pages/videos/[videoId].tsx",
"language": "tsx",
"file_size": 4018,
"cut_index": 614,
"middle_length": 229
} |
xt/link";
export default function Header() {
return (
<header className="w-full bg-white shadow-md py-4 px-8">
<nav className="flex justify-between items-center">
<Link
href="/"
className="text-xl font-bold text-gray-800 hover:text-blue-600 transition-colors"
>
... | ne">
New Post
</Link>
<Link
href="/users/new"
className="bg-blue-500 text-white px-4 py-2 rounded-lg hover:bg-blue-600 transition"
>
New User
</Link>
</div>
| ="/posts/new" className="text-blue-600 hover:underli | {
"filepath": "examples/prisma-postgres/app/Header.tsx",
"language": "tsx",
"file_size": 886,
"cut_index": 547,
"middle_length": 52
} |
import {
BaseClientOptions,
buildClient,
SchemaInference,
XataRecord,
} from "@xata.io/client";
const tables = [
{
name: "nextjs_with_xata_example",
columns: [
{ name: "title", type: "string" },
{ name: "description", type: "string" },
{ name: "url", type: "string" },
],
},
] ... | ons?: BaseClientOptions) {
super({ ...defaultOptions, ...options }, tables);
}
}
let instance: XataClient | undefined = undefined;
export const getXataClient = () => {
if (instance) return instance;
instance = new XataClient();
return instanc | ;
export type NextjsWithXataExampleRecord = NextjsWithXataExample & XataRecord;
const DatabaseClient = buildClient();
const defaultOptions = {};
export class XataClient extends DatabaseClient<SchemaTables> {
constructor(opti | {
"filepath": "examples/with-xata/utils/xata.codegen.ts",
"language": "typescript",
"file_size": 1003,
"cut_index": 512,
"middle_length": 229
} |
ateUser, findUser, validatePassword } from "../lib/user";
import { setLoginSession, getLoginSession } from "../lib/auth";
import { removeTokenCookie } from "../lib/auth-cookies";
import { GraphQLError } from "graphql";
export const resolvers = {
Query: {
async viewer(_root, _args, context, _info) {
try {
... | signUp(_parent, args, _context, _info) {
const user = await createUser(args.input);
return { user };
},
async signIn(_parent, args, context, _info) {
const user = await findUser({ email: args.input.email });
if (user && (a | hQLError(
"Authentication token is invalid, please log in",
{
extensions: {
code: "UNAUTHENTICATED",
},
},
);
}
},
},
Mutation: {
async | {
"filepath": "examples/api-routes-apollo-server-and-client-auth/apollo/resolvers.ts",
"language": "typescript",
"file_size": 1443,
"cut_index": 524,
"middle_length": 229
} |
uth, signIn, signOut } from "@/auth";
function SignIn() {
return (
<form
action={async () => {
"use server";
await signIn("github");
}}
>
<p>You are not logged in</p>
<button type="submit">Sign in with GitHub</button>
</form>
);
}
function SignOut({ children }: ... | button>
</form>
);
}
export default async function Page() {
let session = await auth();
let user = session?.user?.email;
return (
<section>
<h1>Home</h1>
<div>{user ? <SignOut>{`Welcome ${user}`}</SignOut> : <SignIn />}</div>
| it">Sign out</ | {
"filepath": "examples/auth/app/page.tsx",
"language": "tsx",
"file_size": 814,
"cut_index": 522,
"middle_length": 14
} |
ort Image from "next/image";
import type {
Product as ProductType,
Category,
} from "@/lib/generated/prisma/client";
type ProductWithCategory = ProductType & {
category: Category | null;
};
export function Product({ product }: { product: ProductWithCategory }) {
const { name, description, price, image, catego... | "text-gray-900 text-xl">${price.toString()}</p>
</div>
<div className="px-6 pt-4 pb-2">
{category && (
<span className="inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700 mr-2 mb-2">
| src={image}
alt={name}
/>
<div className="px-6 py-4">
<div className="font-bold text-xl mb-2">{name}</div>
<p className="text-gray-700 text-base">{description}</p>
<p className= | {
"filepath": "examples/with-mysql/components/Product.tsx",
"language": "tsx",
"file_size": 1078,
"cut_index": 515,
"middle_length": 229
} |
orce-dynamic"; // This disables SSG and ISR
import prisma from "@/lib/prisma";
import { notFound, redirect } from "next/navigation";
export default async function Post({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const postId = parseInt(id);
const post = await prisma.po... | enter p-8">
<article className="max-w-3xl w-full bg-white shadow-lg rounded-lg p-8">
{/* Post Title */}
<h1 className="text-5xl font-extrabold text-blue-600 mb-4">
{post.title}
</h1>
{/* Author Information * | t() {
"use server";
await prisma.post.delete({
where: {
id: postId,
},
});
redirect("/posts");
}
return (
<div className="min-h-screen bg-gray-50 flex flex-col items-center justify-c | {
"filepath": "examples/prisma-postgres/app/posts/[id]/page.tsx",
"language": "tsx",
"file_size": 1902,
"cut_index": 537,
"middle_length": 229
} |
"alice@example.com", name: "Alice" },
{ email: "bob@example.com", name: "Bob" },
{ email: "charlie@example.com", name: "Charlie" },
{ email: "diana@example.com", name: "Diana" },
{ email: "edward@example.com", name: "Edward" },
],
});
// Find all users to get their IDs
const userRecor... | => user.email === "edward@example.com")?.id,
};
// Create 15 posts distributed among users
await prisma.post.createMany({
data: [
// Alice's posts
{
title: "Getting Started with TypeScript and Prisma",
content:
| "bob@example.com")?.id,
charlie: userRecords.find((user) => user.email === "charlie@example.com")
?.id,
diana: userRecords.find((user) => user.email === "diana@example.com")?.id,
edward: userRecords.find((user) | {
"filepath": "examples/prisma-postgres/prisma/seed.ts",
"language": "typescript",
"file_size": 5586,
"cut_index": 716,
"middle_length": 229
} |
D here:
// https://github.com/garmeeh/next-seo#json-ld
export default function JsonLd() {
return (
<div>
<ArticleJsonLd
url="https://example.com/article"
title="Article headline"
images={[
"https://example.com/photos/1x1/photo.jpg",
"https://example.com/photos/4x3... |
publisherLogo="https://www.example.com/photos/logo.jpg"
description="This is a mighty good description of this article."
/>
<h1>JSON-LD Added to Page</h1>
<p>
Take a look at the head to see what has been added, yo | Name="Jane Blogs"
publisherName="Mary Blogs" | {
"filepath": "examples/with-next-seo/pages/jsonld.js",
"language": "javascript",
"file_size": 989,
"cut_index": 582,
"middle_length": 52
} |
;
import { HttpLink } from "@apollo/client";
import {
ApolloNextAppProvider,
NextSSRInMemoryCache,
NextSSRApolloClient,
} from "@apollo/experimental-nextjs-app-support/ssr";
function makeClient() {
const httpLink = new HttpLink({
// See more information about this GraphQL endpoint at https://studio.apollo... | ata fetching hook, e.g.:
// ```js
// const { data } = useSuspenseQuery(
// MY_QUERY,
// {
// context: {
// fetchOptions: {
// cache: "no-store"
// }
// }
// }
// );
// ```
| tchOptions: { cache: "force-cache" },
// alternatively you can override the default `fetchOptions` on a per query basis
// via the `context` property on the options passed as a second argument
// to an Apollo Client d | {
"filepath": "examples/with-apollo/src/components/ApolloClientProvider.tsx",
"language": "tsx",
"file_size": 1365,
"cut_index": 524,
"middle_length": 229
} |
NextPageContext } from 'next'
import Layout from "../../components/Layout";
import { User } from "../../interfaces";
import { findAll, findData } from "../../utils/sample-api";
import ListDetail from "../../components/ListDetail";
import { GetStaticPaths, GetStaticProps } from "next";
type Params = {
id?: string;
};... | t Example`}
>
{item && <ListDetail item={item} />}
</Layout>
);
};
export const getStaticPaths: GetStaticPaths = async () => {
const items: User[] = await findAll();
const paths = items.map((item) => `/detail/${item.id}`);
return { p | + Electron Example`}>
<p>
<span style={{ color: "red" }}>Error:</span> {errors}
</p>
</Layout>
);
}
return (
<Layout
title={`${item ? item.name : "Detail"} | Next.js + TypeScrip | {
"filepath": "examples/with-electron-typescript/renderer/pages/detail/[id].tsx",
"language": "tsx",
"file_size": 1409,
"cut_index": 524,
"middle_length": 229
} |
Native
import { join } from "path";
import { format } from "url";
// Packages
import { BrowserWindow, app, ipcMain, IpcMainEvent } from "electron";
import isDev from "electron-is-dev";
import prepareNext from "electron-next";
// Prepare the renderer once the app is ready
app.on("ready", async () => {
await prepareN... | });
mainWindow.loadURL(url);
});
// Quit the app once all windows are closed
app.on("window-all-closed", app.quit);
// listen the channel `message` and resend the received message to the renderer process
ipcMain.on("message", (event: IpcMainEvent, m | oin(__dirname, "preload.js"),
},
});
const url = isDev
? "http://localhost:8000/"
: format({
pathname: join(__dirname, "../renderer/out/index.html"),
protocol: "file:",
slashes: true,
| {
"filepath": "examples/with-electron-typescript/electron-src/index.ts",
"language": "typescript",
"file_size": 1121,
"cut_index": 515,
"middle_length": 229
} |
ad";
import Image from "next/image";
import styles from "@/pages/index.module.css";
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 className={s... | s and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
<h3>Learn →</h3>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>
<a
hr | de>
</p>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h3>Documentation →</h3>
<p>Find in-depth information about Next.js feature | {
"filepath": "examples/with-jest/pages/home/index.tsx",
"language": "tsx",
"file_size": 1976,
"cut_index": 537,
"middle_length": 229
} |
rom "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link ... | s://nextjs.org/docs" className={styles.card}>
<h2>Documentation →</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
| </h1>
<p className={styles.description}>
Get started by editing{" "}
<code className={styles.code}>pages/index.tsx</code>
</p>
<div className={styles.grid}>
<a href="http | {
"filepath": "examples/with-graphql-gateway/pages/index.tsx",
"language": "tsx",
"file_size": 2360,
"cut_index": 563,
"middle_length": 229
} |
orce-dynamic"; // This disables SSG and ISR
import prisma from "@/lib/prisma";
import { redirect } from "next/navigation";
import Form from "next/form";
export default function NewUser() {
async function createUser(formData: FormData) {
"use server";
const name = formData.get("name") as string;
const e... | t-medium mb-2">
Name
</label>
<input
type="text"
id="name"
name="name"
placeholder="Enter user name ..."
className="w-full px-4 py-2 border rounded-lg"
/> | ite rounded-lg shadow-md mt-12">
<h1 className="text-3xl font-bold mb-6">Create New User</h1>
<Form action={createUser} className="space-y-6">
<div>
<label htmlFor="name" className="block text-lg fon | {
"filepath": "examples/prisma-postgres/app/users/new/page.tsx",
"language": "tsx",
"file_size": 1811,
"cut_index": 537,
"middle_length": 229
} |
ables SSG and ISR
import Form from "next/form";
import prisma from "@/lib/prisma";
import { revalidatePath } from "next/cache";
import { redirect } from "next/navigation";
export default function NewPost() {
async function createPost(formData: FormData) {
"use server";
const authorEmail = (formData.get("au... | ate({
data: postData,
});
revalidatePath("/posts");
redirect("/posts");
}
return (
<div className="max-w-2xl mx-auto p-4">
<h1 className="text-2xl font-bold mb-6">Create New Post</h1>
<Form action={createPost} classN | title,
content,
author: {
connect: {
email: authorEmail,
},
},
}
: {
title,
content,
};
await prisma.post.cre | {
"filepath": "examples/prisma-postgres/app/posts/new/page.tsx",
"language": "tsx",
"file_size": 2636,
"cut_index": 563,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.