prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
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/umbraco-heartcore";
import Head from "next/head";
impo... | ost.title}
coverImage={heroPost.coverImage}
date={heroPost.date}
author={heroPost.author}
slug={heroPost.slug}
excerpt={heroPost.excerpt}
/>
)}
{morePosts | review={preview}>
<Head>
<title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
<Intro />
{heroPost && (
<HeroPost
title={heroP | {
"filepath": "examples/cms-umbraco-heartcore/pages/index.js",
"language": "javascript",
"file_size": 1280,
"cut_index": 524,
"middle_length": 229
} |
xport default 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.UMBRACO_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
... | son({ message: "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 vulnerab | enabled
if (!post) {
return res.status(401).j | {
"filepath": "examples/cms-umbraco-heartcore/pages/api/preview.js",
"language": "javascript",
"file_size": 960,
"cut_index": 582,
"middle_length": 52
} |
;
import { atom, useAtom } from "jotai";
type Point = [number, number];
const dotsAtom = atom<Point[]>([]);
const drawingAtom = atom<boolean>(false);
const handleMouseDownAtom = atom(null, (get, set) => {
set(drawingAtom, true);
});
const handleMouseUpAtom = atom(null, (get, set) => {
set(drawingAtom, false);
... | lt function Canvas() {
const [, handleMouseUp] = useAtom(handleMouseUpAtom);
const [, handleMouseDown] = useAtom(handleMouseDownAtom);
const [, handleMouseMove] = useAtom(handleMouseMoveAtom);
return (
<svg
width="100vw"
height="100 | onst SvgDots = () => {
const [dots] = useAtom(handleMouseMoveAtom);
return (
<g>
{dots.map(([x, y], index) => (
<circle cx={x} cy={y} r="2" fill="#aaa" key={index} />
))}
</g>
);
};
export defau | {
"filepath": "examples/with-jotai/components/Canvas.tsx",
"language": "tsx",
"file_size": 1303,
"cut_index": 524,
"middle_length": 229
} |
ule.css";
import "../styles/globals.css";
import Canvas from "../components/Canvas";
import { Metadata } from "next";
export const metadata: Metadata = {
title: "with-jotai",
description: "Generated by create next app",
};
export default function Home() {
return (
<div className={styles.container}>
<h... | m=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{" "}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} he | ps://vercel.com?utm_source=create-next-app&utm_mediu | {
"filepath": "examples/with-jotai/app/page.tsx",
"language": "tsx",
"file_size": 968,
"cut_index": 582,
"middle_length": 52
} |
ort {
action,
observable,
computed,
runInAction,
makeObservable,
} from "mobx";
import { enableStaticRendering } from "mobx-react-lite";
enableStaticRendering(typeof window === "undefined");
export class Store {
lastUpdate = 0;
light = false;
constructor() {
makeObservable(this, {
lastUpdat... | ())}:${pad(t.getUTCMinutes())}:${pad(
t.getUTCSeconds(),
)}`;
return format(new Date(this.lastUpdate));
}
stop = () => clearInterval(this.timer);
hydrate = (data) => {
if (!data) return;
this.lastUpdate = data.lastUpdate | ction(() => {
this.lastUpdate = Date.now();
this.light = true;
});
}, 1000);
};
get timeString() {
const pad = (n) => (n < 10 ? `0${n}` : n);
const format = (t) =>
`${pad(t.getUTCHours | {
"filepath": "examples/with-mobx/store.js",
"language": "javascript",
"file_size": 1079,
"cut_index": 515,
"middle_length": 229
} |
mport { createContext, useContext } from "react";
import { Store } from "../store";
let store;
export const StoreContext = createContext();
export function useStore() {
const context = useContext(StoreContext);
if (context === undefined) {
throw new Error("useStore must be used within StoreProvider");
}
... | tore;
// Create the store once in the client
if (!store) store = _store;
return _store;
}
export function StoreProvider({ children, initialState: initialData }) {
const store = initializeStore(initialData);
return (
<StoreContext.Provider | / get hydrated here, check `pages/ssg.js` and `pages/ssr.js` for more details
if (initialData) {
_store.hydrate(initialData);
}
// For SSG and SSR always create a new store
if (typeof window === "undefined") return _s | {
"filepath": "examples/with-mobx/components/StoreProvider.js",
"language": "javascript",
"file_size": 1054,
"cut_index": 513,
"middle_length": 229
} |
ort React from "react";
import PropTypes from "prop-types";
import { kea } from "kea";
const logic = kea({
path: () => ["kea"],
actions: () => ({
increment: (amount) => ({ amount }),
decrement: (amount) => ({ amount }),
}),
reducers: ({ actions }) => ({
counter: [
0,
PropTypes.number,
... | <p>Double Counter: {this.props.doubleCounter}</p>
<button type="button" onClick={() => this.actions.increment(1)}>
Increment
</button>
<button type="button" onClick={() => this.actions.decrement(1)}>
Decr | electors }) => ({
doubleCounter: [
() => [selectors.counter],
(counter) => counter * 2,
PropTypes.number,
],
}),
});
@logic
class Index extends React.Component {
render() {
return (
<div>
| {
"filepath": "examples/with-kea/pages/index.js",
"language": "javascript",
"file_size": 1073,
"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-cosmic/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
from "interfaces";
import ErrorPage from "next/error";
const BUCKET_SLUG = process.env.COSMIC_BUCKET_SLUG;
const READ_KEY = process.env.COSMIC_READ_KEY;
const bucket = Cosmic().bucket({
slug: BUCKET_SLUG,
read_key: READ_KEY,
});
export const getPreviewPostBySlug = async (slug: string) => {
const params = {
... | slug",
};
const data = await bucket.getObjects(params);
return data.objects;
};
export const getAllPostsForHome = async (
preview: boolean,
): Promise<PostType[]> => {
const params = {
query: {
type: "posts",
},
props: "title,s | rr) {
// Don't throw if an slug doesn't exist
return <ErrorPage statusCode={err.status} />;
}
};
export const getAllPostsWithSlug = async () => {
const params = {
query: {
type: "posts",
},
props: " | {
"filepath": "examples/cms-cosmic/lib/api.tsx",
"language": "tsx",
"file_size": 2096,
"cut_index": 563,
"middle_length": 229
} |
iner from "./container";
import cn from "classnames";
import { EXAMPLE_PATH } from "@/lib/constants";
type AlertProps = {
preview: boolean;
};
const Alert = (props: AlertProps) => {
const { preview } = props;
return (
<div
className={cn("border-b", {
"bg-accent-7 border-accent-7 text-white": p... | </a>{" "}
to exit preview mode.
</>
) : (
<>
The source code for this blog is{" "}
<a
href={`https://github.com/vercel/next.js/tree/canary/examples/${EXAMPLE_PATH | This page is a preview.{" "}
<a
href="/api/exit-preview"
className="underline hover:text-cyan duration-200 transition-colors"
>
Click here
| {
"filepath": "examples/cms-cosmic/components/alert.tsx",
"language": "tsx",
"file_size": 1293,
"cut_index": 524,
"middle_length": 229
} |
ype CoverImageProps = {
title;
url;
slug;
};
const CoverImage = (props: CoverImageProps) => {
const { title, url, slug } = props;
const image = (
<Imgix
src={url}
alt={`Cover Image for ${title}`}
className={cn("lazyload shadow-small w-full", {
"hover:shadow-medium transition-sha... | blur=500&w=auto`,
}}
/>
);
return (
<div className="sm:mx-0">
{slug ? (
<Link href={`/posts/${slug}`} aria-label={title}>
{image}
</Link>
) : (
image
)}
</div>
);
};
export default | es={{
src: `${url}?auto=format,compress&q=1& | {
"filepath": "examples/cms-cosmic/components/cover-image.tsx",
"language": "tsx",
"file_size": 927,
"cut_index": 606,
"middle_length": 52
} |
Container from "./container";
import { EXAMPLE_PATH } from "@/lib/constants";
const 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-5xl font-bold... | ck 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/${EXAMPLE_PAT | 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 border border-bla | {
"filepath": "examples/cms-cosmic/components/footer.tsx",
"language": "tsx",
"file_size": 1222,
"cut_index": 518,
"middle_length": 229
} |
r from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import Link from "next/link";
import { AuthorType, ImgixType } from "interfaces";
type HeroPostProps = {
title: string;
coverImage: ImgixType;
date: string;
excerpt: string;
author: AuthorType;
slug: string;
};
const Her... | >
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="mb-4 md:mb-0 text-lg">
<Date dateString={date} />
</div>
</div>
| e={title} url={coverImage.imgix_url} 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-4 text-4xl lg:text-6xl leading-tight" | {
"filepath": "examples/cms-cosmic/components/hero-post.tsx",
"language": "tsx",
"file_size": 1282,
"cut_index": 524,
"middle_length": 229
} |
, CMS_URL } from "@/lib/constants";
const 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="text-... | Next.js
</a>{" "}
and{" "}
<a
href={CMS_URL}
className="underline hover:text-success duration-200 transition-colors"
>
{CMS_NAME}
</a>
.
</h4>
</section>
);
};
e | ess duration-200 transition-colors"
>
| {
"filepath": "examples/cms-cosmic/components/intro.tsx",
"language": "tsx",
"file_size": 858,
"cut_index": 529,
"middle_length": 52
} |
from "next/head";
import { CMS_NAME, HOME_OG_IMAGE_URL } from "@/lib/constants";
const Meta = () => {
return (
<Head>
<link
rel="apple-touch-icon"
sizes="180x180"
href="/favicon/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
sizes="32x... | />
<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/rss+xml" href | ink rel="manifest" href="/favicon/site.webmanifest" />
<link
rel="mask-icon"
href="/favicon/safari-pinned-tab.svg"
color="#000000"
/>
<link rel="shortcut icon" href="/favicon/favicon.ico" | {
"filepath": "examples/cms-cosmic/components/meta.tsx",
"language": "tsx",
"file_size": 1265,
"cut_index": 524,
"middle_length": 229
} |
ostPreview from "./post-preview";
type MoreStoriesProps = {
posts: PostType[];
};
const MoreStories = (props: MoreStoriesProps) => {
const { posts } = props;
return (
<section>
<h2 className="mb-8 text-6xl md:text-7xl font-bold tracking-tighter leading-tight">
More Stories
</h2>
<d... | adata.cover_image}
date={post.created_at}
author={post.metadata.author}
slug={post.slug}
excerpt={post.metadata.excerpt}
/>
))}
</div>
</section>
);
};
export default MoreStorie | title={post.title}
coverImage={post.met | {
"filepath": "examples/cms-cosmic/components/more-stories.tsx",
"language": "tsx",
"file_size": 870,
"cut_index": 559,
"middle_length": 52
} |
Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import PostTitle from "./post-title";
import { AuthorType, ImgixType } from "interfaces";
type PostHeaderProps = {
title: string;
coverImage: ImgixType;
date: string;
author: AuthorType;
};
const PostHeader = (props: P... |
</div>
<div className="max-w-2xl mx-auto">
<div className="block md:hidden mb-6">
<Avatar
name={author.title}
picture={author.metadata.picture.imgix_url}
/>
</div>
<div classN | r
name={author.title}
picture={author.metadata.picture.imgix_url}
/>
</div>
<div className="mb-8 md:mb-16 sm:mx-0">
<CoverImage title={title} url={coverImage.imgix_url} slug={""} /> | {
"filepath": "examples/cms-cosmic/components/post-header.tsx",
"language": "tsx",
"file_size": 1132,
"cut_index": 518,
"middle_length": 229
} |
import Avatar from "./avatar";
import Date from "./date";
import CoverImage from "./cover-image";
import Link from "next/link";
import { AuthorType, ImgixType } from "interfaces";
type PostPreviewProps = {
title: string;
coverImage: ImgixType;
date: string;
excerpt: string;
author: AuthorType;
slug: string... | </h3>
<div className="text-lg mb-4">
<Date dateString={date} />
</div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
<Avatar name={author.title} picture={author.metadata.picture.imgix_url} />
</div>
);
};
| age slug={slug} title={title} url={coverImage.imgix_url} />
</div>
<h3 className="text-3xl mb-3 leading-snug">
<Link href={`/posts/${slug}`} className="hover:underline">
{title}
</Link>
| {
"filepath": "examples/cms-cosmic/components/post-preview.tsx",
"language": "tsx",
"file_size": 1026,
"cut_index": 512,
"middle_length": 229
} |
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 } from "@/lib/const... | <Container>
<Intro />
{heroPost && (
<HeroPost
title={heroPost.title}
coverImage={heroPost.metadata.cover_image}
date={heroPost.created_at}
author={heroPost.metadata. |
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-cosmic/pages/index.tsx",
"language": "tsx",
"file_size": 1548,
"cut_index": 537,
"middle_length": 229
} |
c 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.COSMIC_PREVIEW_SECRET ||
!req.query.slug
) {
return res.status(401).json({ message: "Invalid token" });
}
// Fetch the h... | alid 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
res.write | t) {
return res.status(401).json({ message: "Inv | {
"filepath": "examples/cms-cosmic/pages/api/preview.ts",
"language": "typescript",
"file_size": 953,
"cut_index": 582,
"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-se... | e;
morePosts: PostType[];
preview;
};
const Post = (props: PostProps) => {
const { post, morePosts, preview } = props;
const router = useRouter();
if (!router.isFallback && !post?.slug) {
return <ErrorPage statusCode={404} />;
}
return ( | t/head";
import { CMS_NAME } from "@/lib/constants";
import markdownToHtml from "@/lib/markdownToHtml";
import { PostType } from "interfaces";
import { ParsedUrlQueryInput } from "querystring";
type PostProps = {
post: PostTyp | {
"filepath": "examples/cms-cosmic/pages/posts/[slug].tsx",
"language": "tsx",
"file_size": 2830,
"cut_index": 563,
"middle_length": 229
} |
{ Html, Head, Main, NextScript } from "next/document";
import { renderToNodeList } from "react-fela";
import getFelaRenderer from "../getFelaRenderer";
export default class MyDocument extends Document {
static async getInitialProps(ctx) {
const renderer = getFelaRenderer();
const originalRenderPage = ctx.re... | oNodeList(renderer);
return {
...initialProps,
styles: [...initialProps.styles, ...styles],
};
}
render() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
| ent.getInitialProps(ctx);
const styles = renderT | {
"filepath": "examples/with-fela/pages/_document.js",
"language": "javascript",
"file_size": 859,
"cut_index": 529,
"middle_length": 52
} |
setRandomNumber] = useState(null);
const recalculate = () => {
setRandomNumber(Math.ceil(Math.random() * 100));
};
useEffect(() => {
recalculate();
}, []);
const message = do {
if (randomNumber < 30) {
// eslint-disable-next-line no-unused-expressions
("Do not give up. Try again.");... | andomNumber === null) return <p>Please wait..</p>;
return (
<div>
<h3>Your Lucky number is: "{randomNumber}"</h3>
<p>{message}</p>
<button onClick={() => recalculate()}>Try Again</button>
</div>
);
};
export default MyLuckNo; |
("You are soooo lucky!");
}
};
if (r | {
"filepath": "examples/with-custom-babel-config/pages/index.js",
"language": "javascript",
"file_size": 915,
"cut_index": 606,
"middle_length": 52
} |
<p className="description">
Get started by editing <code>app/page.tsx</code>
</p>
<div className="grid">
<a href="https://nextjs.org/docs" className="card">
<h3>Documentation →</h3>
<p>Find in-depth information about Next.js features and API.</p>
... | Next.js projects.</p>
</a>
<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
| </a>
<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className="card"
>
<h3>Examples →</h3>
<p>Discover and deploy boilerplate example | {
"filepath": "examples/with-sitemap/app/page.tsx",
"language": "tsx",
"file_size": 5099,
"cut_index": 716,
"middle_length": 229
} |
from "react";
import {
ComponentParams,
ComponentRendering,
Placeholder,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface ComponentProps {
rendering: ComponentRendering & { params: ComponentParams };
params: ComponentParams;
}
export const Default = (props: ComponentProps): JSX.Element => {
const st... | s.params.RenderingIdentifier;
return (
<div
className={`component row-splitter ${styles}`}
id={id ? id : undefined}
>
{enabledPlaceholders.map((ph, index) => {
const phKey = `row-${ph}-{*}`;
const phStyles = `${ | ,
props.params.Styles4,
props.params.Styles5,
props.params.Styles6,
props.params.Styles7,
props.params.Styles8,
];
const enabledPlaceholders = props.params.EnabledPlaceholders.split(",");
const id = prop | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/RowSplitter.tsx",
"language": "tsx",
"file_size": 1475,
"cut_index": 524,
"middle_length": 229
} |
config";
import {
GraphQLErrorPagesService,
SitecoreContext,
ErrorPages,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { SitecorePageProps } from "lib/page-props";
import NotFound from "src/NotFound";
import { componentFactory } from "temp/componentFactory";
import Layout from "src/Layout";
import { GetStati... | Props: GetStaticProps = async (context) => {
const site = siteResolver.getByName(config.jssAppName);
const errorPagesService = new GraphQLErrorPagesService({
endpoint: config.graphQLEndpoint,
apiKey: config.sitecoreApiKey,
siteName: site.na | nd />;
}
return (
<SitecoreContext
componentFactory={componentFactory}
layoutData={props.layoutData}
>
<Layout layoutData={props.layoutData} />
</SitecoreContext>
);
};
export const getStatic | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/404.tsx",
"language": "tsx",
"file_size": 1514,
"cut_index": 537,
"middle_length": 229
} |
ad";
import {
GraphQLErrorPagesService,
SitecoreContext,
ErrorPages,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { SitecorePageProps } from "lib/page-props";
import Layout from "src/Layout";
import { componentFactory } from "temp/componentFactory";
import { GetStaticProps } from "next";
import config from ... | <a href="/">Go to the Home page</a>
</div>
</>
);
const Custom500 = (props: SitecorePageProps): JSX.Element => {
if (!(props && props.layoutData)) {
return <ServerError />;
}
return (
<SitecoreContext
componentFactory={com | rver Error</title>
</Head>
<div style={{ padding: 10 }}>
<h1>500 Internal Server Error</h1>
<p>
There is a problem with the resource you are looking for, and it cannot
be displayed.
</p>
| {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/500.tsx",
"language": "tsx",
"file_size": 1956,
"cut_index": 537,
"middle_length": 229
} |
piResponse } from "next";
import { GraphQLRobotsService } from "@sitecore-jss/sitecore-jss-nextjs";
import { siteResolver } from "lib/site-resolver";
import config from "temp/config";
const robotsApi = async (
req: NextApiRequest,
res: NextApiResponse,
): Promise<void> => {
// Ensure response is text/html
res.... | e
const robotsService = new GraphQLRobotsService({
endpoint: config.graphQLEndpoint,
apiKey: config.sitecoreApiKey,
siteName: site.name,
});
const robotsResult = await robotsService.fetchRobots();
return res.status(200).send(robotsRes | ByHost(hostName);
// create robots graphql servic | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/robots.ts",
"language": "typescript",
"file_size": 891,
"cut_index": 547,
"middle_length": 52
} |
tingRenderMiddleware } from "@sitecore-jss/sitecore-jss-nextjs/editing";
/**
* This Next.js API route is used to handle POST requests from Sitecore editors.
* This route should match the `serverSideRenderingEngineEndpointUrl` in your Sitecore configuration,
* which is set to "http://localhost:3000/api/editing/rende... | e render request, passing along the Preview Mode cookies.
* This allows retrieval of the editing data in preview context (via an `EditingDataService`) - see `SitecorePagePropsFactory`
* 5. Return the rendered page HTML to the Sitecore editor
*/
// | data (for later use in the page render request) via an `EditingDataService`, which returns a key for retrieval
* 3. Enable Next.js Preview Mode, passing our stashed editing data key as preview data
* 4. Invoke the actual pag | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/editing/render.ts",
"language": "typescript",
"file_size": 1425,
"cut_index": 524,
"middle_length": 229
} |
e-jss/sitecore-jss-nextjs/editing";
/**
* This Next.js API route is used to handle Sitecore editor data storage and retrieval by key
* on serverless deployment architectures (e.g. Vercel) via the `ServerlessEditingDataService`.
*
* The `EditingDataMiddleware` expects this dynamic route name to be '[key]' by defaul... | #custom-config
export const config = {
api: {
bodyParser: {
sizeLimit: "2mb",
},
responseLimit: false,
},
};
// Wire up the EditingDataMiddleware handler
const handler = new EditingDataMiddleware().getHandler();
export default handl | e https://nextjs.org/docs/api-routes/request-helpers | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/editing/data/[key].ts",
"language": "typescript",
"file_size": 871,
"cut_index": 559,
"middle_length": 52
} |
ib/makeswift/register-components";
import { Makeswift } from "@makeswift/runtime/next";
import {
GetStaticPathsResult,
GetStaticPropsContext,
GetStaticPropsResult,
} from "next";
import {
Page as MakeswiftPage,
PageProps as MakeswiftPageProps,
} from "@makeswift/runtime/next";
type ParsedUrlQuery = { path?... | MakeswiftPageProps;
export async function getStaticProps(
ctx: GetStaticPropsContext<ParsedUrlQuery>,
): Promise<GetStaticPropsResult<Props>> {
const makeswift = new Makeswift(process.env.MAKESWIFT_SITE_API_KEY!);
const path = "/" + (ctx.params?.pa | = await makeswift.getPages();
return {
paths: pages.map((page) => ({
params: {
path: page.path.split("/").filter((segment) => segment !== ""),
},
})),
fallback: "blocking",
};
}
type Props = | {
"filepath": "examples/cms-makeswift/pages/[[...path]].tsx",
"language": "tsx",
"file_size": 1313,
"cut_index": 524,
"middle_length": 229
} |
ort { initializeApp, getApps } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
export const createFirebaseApp = () => {
const clientCredentials = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.N... | eApp(clientCredentials);
// Check that `window` is in scope for the analytics module!
if (typeof window !== "undefined") {
// Enable analytics. https://firebase.google.com/docs/analytics/get-started
if ("measurementId" in clientCredenti | .env.NEXT_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_MEASUREMENT_ID,
};
if (getApps().length <= 0) {
const app = initializ | {
"filepath": "examples/with-firebase/firebase/clientApp.js",
"language": "javascript",
"file_size": 1068,
"cut_index": 515,
"middle_length": 229
} |
ink from "next/link";
import { useEffect } from "react";
import { useUser } from "../context/userContext";
export default function Home() {
// Our custom hook to get context values
const { loadingUser, user } = useUser();
const profile = { username: "nextjs_user", message: "Awesome!!" };
useEffect(() => {
... | >
<title>Next.js w/ Firebase Client-Side</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 className="title">Next.js w/ Firebase Client-Side</h1>
<p className="description">Fill in your credenti | ser]);
const createUser = async () => {
const db = getFirestore();
await setDoc(doc(db, "profile", profile.username), profile);
alert("User created!!");
};
return (
<div className="container">
<Head | {
"filepath": "examples/with-firebase/pages/index.js",
"language": "javascript",
"file_size": 4907,
"cut_index": 614,
"middle_length": 229
} |
mport { Inter } from "next/font/google";
import { EXAMPLE_PATH, CMS_NAME } from "@/lib/constants";
export const metadata = {
title: `Next.js and ${CMS_NAME} Example`,
description: `This is a blog built with Next.js and ${CMS_NAME}.`,
};
const inter = Inter({
variable: "--font-inter",
subsets: ["latin"],
dis... | >
<div className="flex flex-col lg:flex-row justify-center items-center lg:pl-4 lg:w-1/2">
<a
href="https://nextjs.org/docs"
className="mx-3 bg-black hover:bg-white hover:text-black border border-black text | x flex-col lg:flex-row items-center">
<h3 className="text-4xl lg:text-5xl font-bold tracking-tighter leading-tight text-center lg:text-left mb-10 lg:mb-0 lg:pr-4 lg:w-1/2">
Built with Next.js.
</h3 | {
"filepath": "examples/cms-contentful/app/layout.tsx",
"language": "tsx",
"file_size": 1770,
"cut_index": 537,
"middle_length": 229
} |
from "next/headers";
import Date from "./date";
import CoverImage from "./cover-image";
import Avatar from "./avatar";
import MoreStories from "./more-stories";
import { getAllPosts } from "@/lib/api";
import { CMS_NAME, CMS_URL } from "@/lib/constants";
function Intro() {
return (
<section className="flex-col... | n-200 transition-colors"
>
Next.js
</a>{" "}
and{" "}
<a
href={CMS_URL}
className="underline hover:text-success duration-200 transition-colors"
>
{CMS_NAME}
</a>
| <h2 className="text-center md:text-left text-lg mt-5 md:pl-8">
A statically generated blog example using{" "}
<a
href="https://nextjs.org/"
className="underline hover:text-success duratio | {
"filepath": "examples/cms-contentful/app/page.tsx",
"language": "tsx",
"file_size": 2650,
"cut_index": 563,
"middle_length": 229
} |
messaging";
import firebase from "firebase/app";
import localforage from "localforage";
const firebaseCloudMessaging = {
tokenInlocalforage: async () => {
return localforage.getItem("fcm_token");
},
init: async function () {
firebase.initializeApp({
apiKey: "YOUR-API-KEY",
projectId: "YOUR-P... | it Notification.requestPermission();
const token = await messaging.getToken();
localforage.setItem("fcm_token", token);
console.log("fcm_token", token);
} catch (error) {
console.error(error);
}
},
};
export { firebaseCl | const messaging = firebase.messaging();
awa | {
"filepath": "examples/with-firebase-cloud-messaging/utils/webPush.js",
"language": "javascript",
"file_size": 853,
"cut_index": 529,
"middle_length": 52
} |
<FelaComponent
style={{
maxWidth: 700,
marginLeft: "auto",
marginRight: "auto",
lineHeight: 1.5,
}}
as="div"
>
{children}
</FelaComponent>
);
const textRule = ({ size, theme }) => ({
fontFamily:
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", ... | t { css } = useFela();
return <h1 className={css({ fontSize: size, color: "#555" })}>{children}</h1>;
}
export default function Home() {
return (
<Container>
<Title size={50}>My Title</Title>
<Text>Hi, I am Fela.</Text>
</Containe |
}
function Title({ children, size = 24 }) {
cons | {
"filepath": "examples/with-fela/pages/index.js",
"language": "javascript",
"file_size": 924,
"cut_index": 606,
"middle_length": 52
} |
./styles/Home.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 className={styles.main}>
<h1 className={styles.title}>
Welcome t... | "https://nextjs.org/docs" className={styles.card}>
<h3>Documentation →</h3>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
| C_API_URL}</h3>
<p className={styles.description}>
Get started by editing{" "}
<code className={styles.code}>pages/index.js</code>
</p>
<div className={styles.grid}>
<a href= | {
"filepath": "examples/with-docker-multi-env/pages/index.js",
"language": "javascript",
"file_size": 2280,
"cut_index": 563,
"middle_length": 229
} |
useSitecoreContext,
LinkField,
TextField,
} from "@sitecore-jss/sitecore-jss-nextjs";
interface Fields {
data: {
datasource: {
url: {
path: string;
siteName: string;
};
field: {
jsonValue: {
value: string;
editable: string;
};
};
... | s: ComponentContentProps) => {
const id = props.id;
return (
<div className={`component title ${props.styles}`} id={id ? id : undefined}>
<div className="component-content">
<div className="field-title">{props.children}</div>
</ | };
};
};
};
}
type TitleProps = {
params: { [key: string]: string };
fields: Fields;
};
type ComponentContentProps = {
id: string;
styles: string;
children: JSX.Element;
};
const ComponentContent = (prop | {
"filepath": "examples/cms-sitecore-xmcloud/src/components/Title.tsx",
"language": "tsx",
"file_size": 2146,
"cut_index": 563,
"middle_length": 229
} |
und from "src/NotFound";
import Layout from "src/Layout";
import {
RenderingType,
SitecoreContext,
ComponentPropsContext,
handleEditorFastRefresh,
EditingComponentPlaceholder,
StaticPath,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { SitecorePageProps } from "lib/page-props";
import { sitecorePagePro... | re editors do not support Fast Refresh, need to refresh editor chromes after Fast Refresh finished
handleEditorFastRefresh();
}, []);
if (notFound || !layoutData.sitecore.route) {
// Shouldn't hit this (as long as 'notFound' is being returned | m "temp/componentFactory";
import { sitemapFetcher } from "lib/sitemap-fetcher";
const SitecorePage = ({
notFound,
componentProps,
layoutData,
}: SitecorePageProps): JSX.Element => {
useEffect(() => {
// Since Siteco | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/[[...path]].tsx",
"language": "tsx",
"file_size": 3848,
"cut_index": 614,
"middle_length": 229
} |
sable */
/* tslint:disable */
/**
* This is an autogenerated file created by the Stencil compiler.
* It contains typing information for all components that exist in this project.
*/
import { HTMLStencilElement, JSXBase } from "@stencil/core/internal";
export namespace Components {
interface MyComponent {
/**... | tTagNameMap {
"my-component": HTMLMyComponentElement;
}
}
declare namespace LocalJSX {
interface MyComponent {
/**
* The first name
*/
first?: string;
/**
* The last name
*/
last?: string;
/**
* The mid | terface HTMLMyComponentElement
extends Components.MyComponent,
HTMLStencilElement {}
var HTMLMyComponentElement: {
prototype: HTMLMyComponentElement;
new (): HTMLMyComponentElement;
};
interface HTMLElemen | {
"filepath": "examples/with-stencil/packages/test-component/src/components.d.ts",
"language": "typescript",
"file_size": 1358,
"cut_index": 524,
"middle_length": 229
} |
State, useEffect, createContext, useContext } from "react";
import { createFirebaseApp } from "../firebase/clientApp";
import { getAuth, onAuthStateChanged } from "firebase/auth";
export const UserContext = createContext();
export default function UserContextComp({ children }) {
const [user, setUser] = useState(nul... | // You could also look for the user doc in your Firestore (if you have one):
// const userDoc = await firebase.firestore().doc(`users/${uid}`).get()
setUser({ uid, displayName, email, photoURL });
} else setUser(null);
|
const auth = getAuth(app);
const unsubscriber = onAuthStateChanged(auth, async (user) => {
try {
if (user) {
// User is signed in.
const { uid, displayName, email, photoURL } = user;
| {
"filepath": "examples/with-firebase/context/userContext.js",
"language": "javascript",
"file_size": 1480,
"cut_index": 524,
"middle_length": 229
} |
rom "@contentful/rich-text-react-renderer";
import { BLOCKS } from "@contentful/rich-text-types";
interface Asset {
sys: {
id: string;
};
url: string;
description: string;
}
interface AssetLink {
block: Asset[];
}
interface Content {
json: any;
links: {
assets: AssetLink;
};
}
function RichT... |
return null;
}
export function Markdown({ content }: { content: Content }) {
return documentToReactComponents(content.json, {
renderNode: {
[BLOCKS.EMBEDDED_ASSET]: (node: any) => (
<RichTextAsset
id={node.data.target.sys | t.url} layout="fill" alt={asset.description} />;
} | {
"filepath": "examples/cms-contentful/lib/markdown.tsx",
"language": "tsx",
"file_size": 976,
"cut_index": 582,
"middle_length": 52
} |
from "next/headers";
import MoreStories from "../../more-stories";
import Avatar from "../../avatar";
import Date from "../../date";
import CoverImage from "../../cover-image";
import { Markdown } from "@/lib/markdown";
import { getAllPosts, getPostAndMorePosts } from "@/lib/api";
export async function generateStati... | ext-2xl font-bold leading-tight tracking-tight md:text-4xl md:tracking-tighter">
<Link href="/" className="hover:underline">
Blog
</Link>
.
</h2>
<article>
<h1 className="mb-12 text-center text-6xl font | slug: string };
}) {
const { isEnabled } = draftMode();
const { post, morePosts } = await getPostAndMorePosts(params.slug, isEnabled);
return (
<div className="container mx-auto px-5">
<h2 className="mb-20 mt-8 t | {
"filepath": "examples/cms-contentful/app/posts/[slug]/page.tsx",
"language": "tsx",
"file_size": 2136,
"cut_index": 563,
"middle_length": 229
} |
mport Link from "next/link";
import { useRouter } from "next/router";
export default function Nav() {
const router = useRouter();
return (
<div className="root">
<h2>Default</h2>
<p>
Automatically prefetch pages in the background as soon the Link appears
in the view:
</p>
... | g</p>
<Link prefetch={false} href="/contact">
Contact
</Link>
<style jsx>{`
.root {
border-bottom: 1px solid grey;
padding-bottom: 8px;
}
a {
margin-right: 10px;
}
| href="/about"
onMouseEnter={() => {
router.prefetch("/about");
console.log("prefetching /about!");
}}
>
About
</Link>
<h2>Disable</h2>
<p>Disable prefetchin | {
"filepath": "examples/with-prefetching/components/Nav.tsx",
"language": "tsx",
"file_size": 1029,
"cut_index": 513,
"middle_length": 229
} |
port Head from "next/head";
interface ErrorPageProps {
statusCode?: number | null | undefined;
}
/**
* Rendered for 500 errors on both server and client. Used only in Production mode.
* @link https://nextjs.org/docs/advanced-features/custom-error-page#more-advanced-error-page-customizing
*/
const ErrorPage: Next... | occurred.`
: "A client-side error occurred."}
</p>
<a href="/">Go to the Home page</a>
</div>
</>
);
ErrorPage.getInitialProps = ({ res, err }) => {
const statusCode = res ? res.statusCode : err ? err.statusCode : 404;
ret | Code
? `A server-side ${statusCode} error | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/_error.tsx",
"language": "tsx",
"file_size": 905,
"cut_index": 547,
"middle_length": 52
} |
ort { newE2EPage } from "@stencil/core/testing";
describe("my-component", () => {
it("renders", async () => {
const page = await newE2EPage();
await page.setContent("<my-component></my-component>");
const element = await page.find("my-component");
expect(element).toHaveClass("hydrated");
});
it... | ment.textContent).toEqual(`Hello, World! I'm James`);
component.setProperty("last", "Quincy");
await page.waitForChanges();
expect(element.textContent).toEqual(`Hello, World! I'm James Quincy`);
component.setProperty("middle", "Earl");
| omponent");
const element = await page.find("my-component >>> div");
expect(element.textContent).toEqual(`Hello, World! I'm `);
component.setProperty("first", "James");
await page.waitForChanges();
expect(ele | {
"filepath": "examples/with-stencil/packages/test-component/src/components/my-component/my-component.e2e.ts",
"language": "typescript",
"file_size": 1121,
"cut_index": 515,
"middle_length": 229
} |
nk";
import Avatar from "./avatar";
import DateComponent from "./date";
import CoverImage from "./cover-image";
function PostPreview({
title,
coverImage,
date,
excerpt,
author,
slug,
}: {
title: string;
coverImage: any;
date: string;
excerpt: string;
author: any;
slug: string;
}) {
return (
... | mb-4">{excerpt}</p>
{author && <Avatar name={author.name} picture={author.picture} />}
</div>
);
}
export default function MoreStories({ morePosts }: { morePosts: any[] }) {
return (
<section>
<h2 className="mb-8 text-6xl md:text- | /posts/${slug}`} className="hover:underline">
{title}
</Link>
</h3>
<div className="text-lg mb-4">
<DateComponent dateString={date} />
</div>
<p className="text-lg leading-relaxed | {
"filepath": "examples/cms-contentful/app/more-stories.tsx",
"language": "tsx",
"file_size": 1553,
"cut_index": 537,
"middle_length": 229
} |
v className="container">
<main>
<h1 className="title">
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className="description">Contact Page</p>
</main>
<footer>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default... | enter;
align-items: center;
}
main {
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
fo | ssName="logo" />
</a>
</footer>
<style>{`
.container {
min-height: 100vh;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: c | {
"filepath": "examples/with-sitemap/app/contact/page.tsx",
"language": "tsx",
"file_size": 2681,
"cut_index": 563,
"middle_length": 229
} |
rImage {
url
}
date
author {
name
picture {
url
}
}
excerpt
content {
json
links {
assets {
block {
sys {
id
}
url
description
}
}
}
}
`;
async function fetchGraphQL(query: string, preview = ... | ngify({ query }),
next: { tags: ["posts"] },
},
).then((response) => response.json());
}
function extractPost(fetchResponse: any): any {
return fetchResponse?.data?.postCollection?.items?.[0];
}
function extractPostEntries(fetchResponse: an | Type": "application/json",
Authorization: `Bearer ${
preview
? process.env.CONTENTFUL_PREVIEW_ACCESS_TOKEN
: process.env.CONTENTFUL_ACCESS_TOKEN
}`,
},
body: JSON.stri | {
"filepath": "examples/cms-contentful/lib/api.ts",
"language": "typescript",
"file_size": 2571,
"cut_index": 563,
"middle_length": 229
} |
m "next";
import {
AxiosDataFetcher,
GraphQLSitemapXmlService,
getPublicUrl,
AxiosResponse,
} from "@sitecore-jss/sitecore-jss-nextjs";
import { siteResolver } from "lib/site-resolver";
import config from "temp/config";
const ABSOLUTE_URL_REGEXP = "^(?:[a-z]+:)?//";
const sitemapApi = async (
req: NextApiRe... | itecoreApiKey,
siteName: site.name,
});
// if url has sitemap-{n}.xml type. The id - can be null if it's sitemap.xml request
const sitemapPath = await sitemapXmlService.getSitemap(id as string);
// if sitemap is match otherwise redirect to 40 | t(":")[0] || "localhost";
const site = siteResolver.getByHost(hostName);
// create sitemap graphql service
const sitemapXmlService = new GraphQLSitemapXmlService({
endpoint: config.graphQLEndpoint,
apiKey: config.s | {
"filepath": "examples/cms-sitecore-xmcloud/src/pages/api/sitemap.ts",
"language": "typescript",
"file_size": 2312,
"cut_index": 563,
"middle_length": 229
} |
image";
import Link from "next/link";
import {
InstantSearch,
Hits,
Highlight,
useInstantSearch,
useSearchBox,
} from "react-instantsearch";
import { instantMeiliSearch } from "@meilisearch/instant-meilisearch";
import logo from "../assets/meilisearch.svg";
const INDEX_NAME = "steam-videogames";
const { sea... | Search();
return (
<form noValidate action="" role="search" className="mb-12">
<input
type="search"
value={searchbox.query}
placeholder="Search Steam video games"
onChange={(event) => searchbox.refine(event.curre | name: string;
image: string;
description: string;
genres: string[];
__position: number;
objectID: string;
};
}
const SearchBox = () => {
const searchbox = useSearchBox();
const { status } = useInstant | {
"filepath": "examples/with-meilisearch/src/pages/index.tsx",
"language": "tsx",
"file_size": 2791,
"cut_index": 563,
"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
s... | tle}
</Link>
</h3>
<div className="text-lg mb-4">
<Date dateString={date} />
</div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
{author && <Avatar name={author.name} picture={author.picture} />}
| ${slug}`} className="hover:underline">
{ti | {
"filepath": "examples/cms-agilitycms/components/post-preview.tsx",
"language": "tsx",
"file_size": 854,
"cut_index": 529,
"middle_length": 52
} |
ad";
import ErrorPage from "next/error";
import { useRouter } from "next/router";
import Layout from "../components/layout";
import Container from "../components/container";
import { CMS_NAME } from "../lib/constants";
import { getAgilityPaths, getAgilityPageProps } from "../lib/api";
import usePreviewRedirect from "..... | <title>{`Next.js Blog Example with ${CMS_NAME}`}</title>
</Head>
<Container>
{router.isFallback ? (
<h1>Loading...</h1>
) : (
<CMSPageTemplate
sitemapNode={sitemapNode}
| ame,
preview,
}) {
usePreviewRedirect();
const router = useRouter();
if (!router.isFallback && !page) {
return <ErrorPage statusCode={404} />;
}
return (
<>
<Layout preview={preview}>
<Head>
| {
"filepath": "examples/cms-agilitycms/pages/[...slug].tsx",
"language": "tsx",
"file_size": 1848,
"cut_index": 537,
"middle_length": 229
} |
validatePreview } from "../../lib/api";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse,
) {
// Check the secret and next parameters
// This secret should only be known to this API route and the CMS
//validate our preview key, also validate the requested page to preview exis... | ionResp.message}`);
}
// Enable Draft Mode by setting the cookie
res.setDraftMode({ enable: true });
// Redirect to the slug
if (!("slug" in validationResp)) {
throw new Error("invariant missing slug in validation response");
}
res.writ | p.error) {
return res.status(401).end(`${validat | {
"filepath": "examples/cms-agilitycms/pages/api/preview.ts",
"language": "typescript",
"file_size": 952,
"cut_index": 582,
"middle_length": 52
} |
ort { NextApiRequest, NextApiResponse } from "next";
import { WorkflowClient } from "@temporalio/client";
import { order } from "../../../temporal/src/workflows";
export type Data = {
result: string;
};
function getUserId(token?: string): string {
// TODO if the token is a JWT, decode & verify it. If it's a sessi... | poral Server running locally in Docker
const client = new WorkflowClient();
// Execute the order Workflow and wait for it to finish
const result = await client.execute(order, {
taskQueue: "my-nextjs-project",
workflowId: "my-business-id",
| hod !== "POST") {
res.send({ result: "Error code 405: use POST" });
return;
}
const userId: string = getUserId(req.headers.authorization);
const { itemId, quantity } = JSON.parse(req.body);
// Connect to our Tem | {
"filepath": "examples/with-temporal/pages/api/orders/index.ts",
"language": "typescript",
"file_size": 1088,
"cut_index": 515,
"middle_length": 229
} |
etch";
export type ChargeResult = {
status: string;
errorMessage?: string;
};
export async function chargeUser(
userId: string,
itemId: string,
quantity: number,
): Promise<ChargeResult> {
// TODO send request to the payments service that looks up the user's saved
// payment info and the cost of the ite... | ntInventory(
itemId: string,
quantity: number,
): Promise<boolean> {
// TODO a database request that—in a single operation or transaction—checks
// whether there are `quantity` items remaining, and if so, decreases the
// total. Something like:
| ?status=success");
const body: any = await response.json();
return { status: body.args.status };
} catch (e: any) {
return { status: "failure", errorMessage: e.message };
}
}
export async function checkAndDecreme | {
"filepath": "examples/with-temporal/temporal/src/activities.ts",
"language": "typescript",
"file_size": 1700,
"cut_index": 537,
"middle_length": 229
} |
the activity types
import type * as activities from "./activities.js";
const { chargeUser, checkAndDecrementInventory, incrementInventory } =
proxyActivities<typeof activities>({
startToCloseTimeout: "1 minute",
});
export async function order(
userId: string,
itemId: string,
quantity: number,
): Promi... | antity,
);
if (result.status === "success") {
return `Order successful!`;
} else {
await incrementInventory(itemId, quantity);
return `Unable to complete payment. Error: ${result.errorMessage}`;
}
} else {
return `So | ait chargeUser(
userId,
itemId,
qu | {
"filepath": "examples/with-temporal/temporal/src/workflows.ts",
"language": "typescript",
"file_size": 962,
"cut_index": 582,
"middle_length": 52
} |
return (
<footer>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by <img src="/vercel.svg" alt="Vercel Logo" className="logo" />
</a>
<styl... | footer img {
margin-left: 0.5rem;
}
footer a {
display: flex;
justify-content: center;
align-items: center;
}
.logo {
height: 1em;
}
| er;
align-items: center;
}
| {
"filepath": "examples/with-neo4j/components/footer.js",
"language": "javascript",
"file_size": 896,
"cut_index": 547,
"middle_length": 52
} |
rom "../lib/fetcher";
import Header from "../components/header";
import Footer from "../components/footer";
export default function Home() {
const { data, error, isLoading } = useSWR("/api/movies", fetcher);
if (error) return <div>failed to load</div>;
if (isLoading) return <div>loading...</div>;
if (!data) r... |
<tr>
<th>#</th>
<th>Movie Title</th>
<th>Released</th>
<th>Tagline</th>
<th>Directed</th>
<th>Actors</th>
</tr>
</thead | <main>
<div className="movies">
<div className="subtitle">
<p>
<strong>"Movies"</strong> Neo4j example dataset.
</p>
</div>
<table>
<thead> | {
"filepath": "examples/with-neo4j/pages/index.js",
"language": "javascript",
"file_size": 3616,
"cut_index": 614,
"middle_length": 229
} |
t/link";
import { useRouter } from "next/router";
import useSWR from "swr";
import fetcher from "../../lib/fetcher";
import Header from "../../components/header";
import Footer from "../../components/footer";
export default function Movie() {
const router = useRouter();
const { title } = router.query;
const { da... | <h2>Information</h2>
<div>
<strong>Tagline: </strong>
{data.movie.tagline}
</div>
<div>
<strong>Released: </strong>
{data.movie.released}
</div>
| <Head>
<title>Next with Neo4j</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header title={title} />
<main>
<div className="movie">
<div className="info">
| {
"filepath": "examples/with-neo4j/pages/movie/[title].js",
"language": "javascript",
"file_size": 2628,
"cut_index": 563,
"middle_length": 229
} |
getDriver from "../../../util/neo4j";
const driver = getDriver();
const session = driver.session();
export default async function handler(req, res) {
const {
query: { title },
method,
} = req;
const movieTitle = decodeURIComponent(title);
switch (method) {
case "GET":
try {
const m... | = await transaction.run(cypher, {
movieTitle,
});
const [movie] = movieTxResponse.records.map((r) => r.get("movie"));
return movie;
},
);
const movie = await movieTxResultPromise; | {.*,
actors: [ (actor)-[:ACTED_IN]->(movie) | actor.name ],
directed: [ (director)-[:DIRECTED]->(movie) | director.name ]
} as movie
`;
const movieTxResponse | {
"filepath": "examples/with-neo4j/pages/api/movies/[title].js",
"language": "javascript",
"file_size": 1235,
"cut_index": 518,
"middle_length": 229
} |
getDriver from "../../../util/neo4j";
const driver = getDriver();
const session = driver.session();
export default async function handler(req, res) {
const { method } = req;
switch (method) {
case "GET":
try {
const moviesTxResultPromise = session.readTransaction(
async (transaction)... | s = moviesTxResponse.records.map((r) => r.get("movie"));
return movies;
},
);
const movies = await moviesTxResultPromise;
res.status(200).json({ success: true, movies });
} catch (error) {
res.sta | cted: [ (movie)<-[:DIRECTED]-(director) | director.name ]
} as movie
ORDER BY movie.title ASC
`;
const moviesTxResponse = await transaction.run(cypher);
const movie | {
"filepath": "examples/with-neo4j/pages/api/movies/index.js",
"language": "javascript",
"file_size": 1139,
"cut_index": 518,
"middle_length": 229
} |
getDriver from "../../../util/neo4j";
const driver = getDriver();
const session = driver.session();
export default async function handler(req, res) {
const {
query: { name },
method,
} = req;
const actorName = decodeURIComponent(name);
switch (method) {
case "GET":
try {
const acto... | nst [actor] = actorTxResponse.records.map((r) => r.get("actor"));
return actor;
},
);
const actor = await actorTxResultPromise;
res.status(200).json({ success: true, actor });
} catch (error) {
re | ,
movies: [ (actor)-[:ACTED_IN]->(m) | m.title ]
} as actor
`;
const actorTxResponse = await transaction.run(cypher, {
actorName,
});
co | {
"filepath": "examples/with-neo4j/pages/api/actors/[name].js",
"language": "javascript",
"file_size": 1144,
"cut_index": 518,
"middle_length": 229
} |
t/link";
import { useRouter } from "next/router";
import useSWR from "swr";
import fetcher from "../../lib/fetcher";
import Header from "../../components/header";
import Footer from "../../components/footer";
export default function Actor() {
const router = useRouter();
const { name } = router.query;
const { dat... | <div className="info">
<h2>Information</h2>
<div>
<strong>Born: </strong>
{data.actor.born}
</div>
</div>
<div className="movies">
<h2>Movies</h2>
| rn (
<div className="container">
<Head>
<title>Next with Neo4j</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<Header title={name} />
<main>
<div className="actor">
| {
"filepath": "examples/with-neo4j/pages/actor/[name].js",
"language": "javascript",
"file_size": 2434,
"cut_index": 563,
"middle_length": 229
} |
ink as ChakraLink, Button } from "@chakra-ui/react";
import { Container } from "./Container";
export const CTA = () => (
<Container
flexDirection="row"
position="fixed"
bottom={0}
width="full"
maxWidth="3xl"
py={3}
>
<Button
as={ChakraLink}
isExternal
href="https://ch... |
isExternal
href="https://github.com/vercel/next.js/blob/canary/examples/with-chakra-ui"
variant="solid"
colorScheme="green"
rounded="button"
flexGrow={3}
mx={2}
width="full"
>
View Repo
</Butto | s={ChakraLink} | {
"filepath": "examples/with-chakra-ui/src/components/CTA.tsx",
"language": "tsx",
"file_size": 813,
"cut_index": 522,
"middle_length": 14
} |
ink as ChakraLink,
Text,
Code,
List,
ListIcon,
ListItem,
} from "@chakra-ui/react";
import { CheckCircleIcon, LinkIcon } from "@chakra-ui/icons";
import { Hero } from "../components/Hero";
import { Container } from "../components/Container";
import { Main } from "../components/Main";
import { DarkModeSwitch ... | m>
<ListIcon as={CheckCircleIcon} color="green.500" />
<ChakraLink
isExternal
href="https://chakra-ui.com"
flexGrow={1}
mr={2}
>
Chakra UI <LinkIcon />
</Ch | <Main>
<Text color="text">
Example repository of <Code>Next.js</Code> + <Code>chakra-ui</Code> +{" "}
<Code>TypeScript</Code>.
</Text>
<List spacing={3} my={0} color="text">
<ListIte | {
"filepath": "examples/with-chakra-ui/src/pages/index.tsx",
"language": "tsx",
"file_size": 1445,
"cut_index": 524,
"middle_length": 229
} |
ext/head";
import { useForm, SubmitHandler } from "react-hook-form";
import styles from "../styles/login.module.css";
interface User {
name: string;
}
interface LoginFormValues {
username: string;
password: string;
remember: boolean;
}
export default function Page() {
const [user, setUser] = React.useState... | ount" />
<link rel="icon" href="/favicon.ico" />
</Head>
{user ? (
<div className={styles.greeting}>
<h2>Welcome back, {user.name}!</h2>
</div>
) : (
<form onSubmit={handleSubmit(onSubmit)} classN |
password,
remember,
}) => {
setUser({ name: username });
};
return (
<div className={styles.container}>
<Head>
<title>Login</title>
<meta name="description" content="Login to your acc | {
"filepath": "examples/with-react-hook-form/pages/index.tsx",
"language": "tsx",
"file_size": 2805,
"cut_index": 563,
"middle_length": 229
} |
;
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/with-passport/lib/auth-cookies.js",
"language": "javascript",
"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/with-passport/lib/auth.js",
"language": "javascript",
"file_size": 859,
"cut_index": 529,
"middle_length": 52
} |
import Router from "next/router";
import useSWR from "swr";
const fetcher = (url) =>
fetch(url)
.then((r) => r.json())
.then((data) => {
return { user: data?.user || null };
});
export function useUser({ redirectTo, redirectIfFound } = {}) {
const { data, error } = useSWR("/api/user", fetcher);
... | rectTo && !redirectIfFound && !hasUser) ||
// If redirectIfFound is also set, redirect if the user was found
(redirectIfFound && hasUser)
) {
Router.push(redirectTo);
}
}, [redirectTo, redirectIfFound, finished, hasUser]);
re | set, redirect if the user was not found.
(redi | {
"filepath": "examples/with-passport/lib/hooks.js",
"language": "javascript",
"file_size": 883,
"cut_index": 547,
"middle_length": 52
} |
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({ username, password }) {
// Here you should create the user and save the salt and hashed password (s... | s no data persistence without a proper DB
users.push(user);
return { username, createdAt: Date.now() };
}
// Here you should lookup for the user in your DB
export async function findUser({ username }) {
// This is an in memory store for users, ther | df2Sync(password, salt, 1000, 64, "sha512")
.toString("hex");
const user = {
id: crypto.randomUUID(),
createdAt: Date.now(),
username,
hash,
salt,
};
// This is an in memory store for users, there i | {
"filepath": "examples/with-passport/lib/user.js",
"language": "javascript",
"file_size": 1480,
"cut_index": 524,
"middle_length": 229
} |
nk";
const Form = ({ isLogin, errorMessage, onSubmit }) => (
<form onSubmit={onSubmit}>
<label>
<span>Username</span>
<input type="text" name="username" required />
</label>
<label>
<span>Password</span>
<input type="password" name="password" required />
</label>
{!isLogin... | on type="submit">Signup</button>
</>
)}
</div>
{errorMessage && <p className="error">{errorMessage}</p>}
<style jsx>{`
form,
label {
display: flex;
flex-flow: column;
}
label > span {
| <>
<Link href="/signup">I don't have an account</Link>
<button type="submit">Login</button>
</>
) : (
<>
<Link href="/login">I already have an account</Link>
<butt | {
"filepath": "examples/with-passport/components/form.js",
"language": "javascript",
"file_size": 1759,
"cut_index": 537,
"middle_length": 229
} |
Link from "next/link";
import { useUser } from "../lib/hooks";
const Header = () => {
const user = useUser();
return (
<header>
<nav>
<ul>
<li>
<Link href="/">Home</Link>
</li>
{user ? (
<>
<li>
<Link href="/pro... | ul {
display: flex;
list-style: none;
margin-left: 0;
padding-left: 0;
}
li {
margin-right: 1rem;
}
li:first-child {
margin-left: auto;
}
a {
| <Link href="/login">Login</Link>
</li>
)}
</ul>
</nav>
<style jsx>{`
nav {
max-width: 42rem;
margin: 0 auto;
padding: 0.2rem 1.25rem;
}
| {
"filepath": "examples/with-passport/components/header.js",
"language": "javascript",
"file_size": 1213,
"cut_index": 518,
"middle_length": 229
} |
t Header from "./header";
const Layout = (props) => (
<>
<Head>
<title>With Cookies</title>
</Head>
<Header />
<main>
<div className="container">{props.children}</div>
</main>
<style jsx global>{`
*,
*::before,
*::after {
box-sizing: border-box;
... | sans-serif,
"Apple Color Emoji",
"Segoe UI Emoji",
"Segoe UI Symbol",
"Noto Color Emoji";
}
.container {
max-width: 42rem;
margin: 0 auto;
padding: 2rem 1.25rem;
}
`}< | Neue",
Arial,
Noto Sans,
| {
"filepath": "examples/with-passport/components/layout.js",
"language": "javascript",
"file_size": 896,
"cut_index": 547,
"middle_length": 52
} |
nts/layout";
const Home = () => {
const user = useUser();
return (
<Layout>
<h1>Passport.js Example</h1>
<p>Steps to test the example:</p>
<ol>
<li>Click Login and enter a username and password.</li>
<li>
You'll be redirected to Home. Click on Profile, notice how ... | <>
<p>Currently logged in as:</p>
<pre>{JSON.stringify(user, null, 2)}</pre>
</>
)}
<style jsx>{`
li {
margin-bottom: 0.5rem;
}
pre {
white-space: pre-wrap;
| gin.
</li>
</ol>
{user && (
| {
"filepath": "examples/with-passport/pages/index.js",
"language": "javascript",
"file_size": 985,
"cut_index": 582,
"middle_length": 52
} |
State } from "react";
import Router from "next/router";
import { useUser } from "../lib/hooks";
import Layout from "../components/layout";
import Form from "../components/form";
const Login = () => {
useUser({ redirectTo: "/", redirectIfFound: true });
const [errorMsg, setErrorMsg] = useState("");
async functi... | Router.push("/");
} else {
throw new Error(await res.text());
}
} catch (error) {
console.error("An unexpected error happened occurred:", error);
setErrorMsg(error.message);
}
}
return (
<Layout>
| lue,
};
try {
const res = await fetch("/api/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.status === 200) {
| {
"filepath": "examples/with-passport/pages/login.js",
"language": "javascript",
"file_size": 1373,
"cut_index": 524,
"middle_length": 229
} |
"react";
import Router from "next/router";
import { useUser } from "../lib/hooks";
import Layout from "../components/layout";
import Form from "../components/form";
const Signup = () => {
useUser({ redirectTo: "/", redirectIfFound: true });
const [errorMsg, setErrorMsg] = useState("");
async function handleSub... | { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
if (res.status === 200) {
Router.push("/login");
} else {
throw new Error(await res.text());
}
} catch (error) {
console.error |
if (body.password !== e.currentTarget.rpassword.value) {
setErrorMsg(`The passwords don't match`);
return;
}
try {
const res = await fetch("/api/signup", {
method: "POST",
headers: | {
"filepath": "examples/with-passport/pages/signup.js",
"language": "javascript",
"file_size": 1519,
"cut_index": 537,
"middle_length": 229
} |
";
import { localStrategy } from "../../lib/password-local";
import { setLoginSession } from "../../lib/auth";
const authenticate = (method, req, res) =>
new Promise((resolve, reject) => {
passport.authenticate(method, { session: false }, (error, token) => {
if (error) {
reject(error);
} else... | );
// session is the payload to save in the token, it may contain basic info about the user
const session = { ...user };
await setLoginSession(res, session);
res.status(200).send({ done: true });
} catch (error) {
consol | const user = await authenticate("local", req, res | {
"filepath": "examples/with-passport/pages/api/login.js",
"language": "javascript",
"file_size": 961,
"cut_index": 582,
"middle_length": 52
} |
from "next/link";
import {
Generic,
Container,
Content,
Navbar,
Section,
Hero,
Title,
Footer,
} from "rbx";
const Layout = ({ children }) => {
return (
<Generic>
<Navbar fixed="top" color="primary">
<Navbar.Brand>
<Navbar.Item href="#">Bulma</Navbar.Item>
<Navbar... | </Navbar.Menu>
</Navbar>
<Section backgroundColor="primary">
<Hero>
<Hero.Body>
<Container>
<Title as="h1" align="center" color="white">
Welcome to Next!
</Title>
| <Navbar.Item as={Link} href="/about">
About
</Navbar.Item>
<Navbar.Item as={Link} href="/contact">
Contact
</Navbar.Item>
</Navbar.Segment>
| {
"filepath": "examples/with-rbx-bulma-pro/components/Layout.js",
"language": "javascript",
"file_size": 1354,
"cut_index": 524,
"middle_length": 229
} |
ort {
Section,
Title,
Field,
Label,
Control,
Input,
Textarea,
Button,
} from "rbx";
import Layout from "../components/Layout";
const ContactPage = () => (
<Layout>
<Section>
<Title as="h2">Contact Form Example</Title>
<Field>
<Label>Name</Label>
<Control>
<In... | eld>
<Field>
<Label>Message</Label>
<Control>
<Textarea name="message" rows={10} placeholder="your message" />
</Control>
</Field>
<Button.Group align="right">
<Button color="primary" key="submit" | placeholder="your email" />
</Control>
</Field>
<Field>
<Label>Subject</Label>
<Control>
<Input type="text" name="subject" placeholder="your subject" />
</Control>
</Fi | {
"filepath": "examples/with-rbx-bulma-pro/pages/contact.js",
"language": "javascript",
"file_size": 1118,
"cut_index": 515,
"middle_length": 229
} |
from "next/link";
import { Section, Card, Content, Title } from "rbx";
import Layout from "../components/Layout";
const Home = () => (
<Layout>
<Section>
<Card>
<Card.Content>
<Content>
<Link href="https://github.com/vercel/next.js#getting-started">
<Title as="h3... | example boilerplates on the{" "}
<code>create-next-app</code> site
</p>
</Link>
</Content>
</Card.Content>
</Card>
<Card>
<Card.Content>
<Content>
<Link | <Card>
<Card.Content>
<Content>
<Link href="https://github.com/vercel/next.js/tree/canary/examples">
<Title as="h3">Examples →</Title>
<p>
Find other | {
"filepath": "examples/with-rbx-bulma-pro/pages/index.js",
"language": "javascript",
"file_size": 1357,
"cut_index": 524,
"middle_length": 229
} |
om "next/image";
import styles from "@/styles/Home.module.css";
import { Inter } from "next/font/google";
import { connectToElasticsearch } from "@/lib/elasticsearch";
const inter = Inter({ subsets: ["latin"] });
type HomePageProps = InferGetServerSidePropsType<typeof getServerSideProps>;
export default function Hom... | ext app" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<div className={styles.description}>
<p>
| the{" "}
<code className={styles.code}>README.md</code> for instructions.
</p>
);
return (
<>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create n | {
"filepath": "examples/with-elasticsearch/pages/index.tsx",
"language": "tsx",
"file_size": 4968,
"cut_index": 614,
"middle_length": 229
} |
;
import Link, { LinkProps } from "next/link";
import React, { PropsWithChildren, useEffect, useState } from "react";
import { usePathname } from "next/navigation";
const getLinkUrl = (href: LinkProps["href"], as?: LinkProps["as"]): string => {
// Dynamic route will be matched via props.as
// Static route will be... | > {
if (pathname) {
const linkUrl = getLinkUrl(props.href, props.as);
const linkPathname = new URL(linkUrl, location.href).pathname;
const activePathname = new URL(pathname, location.href).pathname;
const newClassName =
| = ({
children,
activeClassName,
className,
...props
}: PropsWithChildren<ActiveLinkProps>) => {
const pathname = usePathname();
const [computedClassName, setComputedClassName] = useState(className);
useEffect(() = | {
"filepath": "examples/active-class-name/components/ActiveLink.tsx",
"language": "tsx",
"file_size": 1471,
"cut_index": 524,
"middle_length": 229
} |
"react";
import { UniversalPortal } from "@jesstelford/react-portal-universal";
const Index = () => {
const [isOpen, toggle] = useState(true);
return (
<>
{/* A portal that is adjacent to its target */}
<div id="target" />
<UniversalPortal selector="#target">
<h1>Hello Portal</h1>
... | : 0,
bottom: 0,
left: 0,
}}
>
<div
style={{
backgroundColor: "white",
position: "absolute",
top: "10%",
right: "10%" | n>
{isOpen && (
<UniversalPortal selector="#modal">
<div
style={{
position: "fixed",
backgroundColor: "rgba(0, 0, 0, 0.7)",
top: 0,
right | {
"filepath": "examples/with-portals-ssr/pages/index.js",
"language": "javascript",
"file_size": 1665,
"cut_index": 537,
"middle_length": 229
} |
import gql from "graphql-tag";
export const SeoQuery = gql`
query SeoQuery(
$slug: ID!
$idType: ContentNodeIdTypeEnum
$preview: Boolean = false
) {
contentNode(id: $slug, idType: $idType, asPreview: $preview) {
seo {
canonical
cornerstone
focuskw
metaDesc
... | tText
mediaDetails {
height
width
}
sourceUrl
}
twitterImage {
altText
mediaDetails {
width
height
}
sourceUrl
}
| pengraphPublisher
opengraphSiteName
opengraphTitle
opengraphType
opengraphUrl
readingTime
title
twitterDescription
twitterTitle
opengraphImage {
al | {
"filepath": "examples/cms-wordpress/src/queries/general/SeoQuery.ts",
"language": "typescript",
"file_size": 1017,
"cut_index": 512,
"middle_length": 229
} |
ort type { Metadata } from "next";
import { print } from "graphql/language/printer";
import { setSeoData } from "@/utils/seoData";
import { fetchGraphQL } from "@/utils/fetchGraphQL";
import { ContentNode, Page } from "@/gql/graphql";
import { PageQuery } from "@/components/Templates/Page/PageQuery";
import { SeoQuer... | cal: `${process.env.NEXT_PUBLIC_BASE_URL}/404-not-found/`,
},
} as Metadata;
}
export default async function NotFound() {
const { page } = await fetchGraphQL<{ page: Page }>(print(PageQuery), {
id: notFoundPageWordPressId,
});
return <div | ntNode: ContentNode }>(
print(SeoQuery),
{ slug: notFoundPageWordPressId, idType: "DATABASE_ID" },
);
const metadata = setSeoData({ seo: contentNode.seo });
return {
...metadata,
alternates: {
canoni | {
"filepath": "examples/cms-wordpress/src/app/not-found.tsx",
"language": "tsx",
"file_size": 1065,
"cut_index": 515,
"middle_length": 229
} |
from "next";
export const revalidate = 0;
async function getTotalCounts() {
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/wp-json/sitemap/v1/totalpages`,
);
const data = await response.json();
if (!data) return [];
const propertyNames = Object.keys(data);
const excludeIt... | L}/wp-json/sitemap/v1/posts?pageNo=${page}&postType=${type}&perPage=${perPage}`,
);
const data = await response.json();
if (!data) return [];
const posts = data.map((post: any) => {
return {
url: `${process.env.NEXT_PUBLIC_BASE_URL}${p | });
return totalArray;
}
async function getPostsUrls({
page,
type,
perPage,
}: {
page: number;
type: string;
perPage: number;
}) {
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_UR | {
"filepath": "examples/cms-wordpress/src/app/sitemap.ts",
"language": "typescript",
"file_size": 1810,
"cut_index": 537,
"middle_length": 229
} |
{ NextRequest, NextResponse } from "next/server";
import { revalidatePath, revalidateTag } from "next/cache";
export async function PUT(request: NextRequest) {
const requestBody = await request.text();
const { paths, tags } = requestBody
? JSON.parse(requestBody)
: { paths: [], tags: [] };
let revalidat... | ay.isArray(tags) && tags.length > 0) {
Promise.all(tags.map((tag) => revalidateTag(tag)));
console.log("Revalidated tags:", tags);
revalidated = true;
}
return NextResponse.json({
revalidated,
now: Date.now(),
p | try {
if (paths && Array.isArray(paths) && paths.length > 0) {
Promise.all(paths.map((path) => revalidatePath(path)));
console.log("Revalidated paths:", paths);
revalidated = true;
}
if (tags && Arr | {
"filepath": "examples/cms-wordpress/src/app/api/revalidate/route.ts",
"language": "typescript",
"file_size": 1176,
"cut_index": 518,
"middle_length": 229
} |
ftMode, cookies } from "next/headers";
export async function fetchGraphQL<T = any>(
query: string,
variables?: { [key: string]: any },
headers?: { [key: string]: string },
): Promise<T> {
const { isEnabled: preview } = draftMode();
try {
let authHeader = "";
if (preview) {
const auth = cookies... | ...(authHeader && { Authorization: authHeader }),
...headers,
},
body,
cache: preview ? "no-cache" : "default",
next: {
tags: ["wordpress"],
},
},
);
if (!response.ok) {
con | ariables,
},
});
const response = await fetch(
`${process.env.NEXT_PUBLIC_WORDPRESS_API_URL}/graphql`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
| {
"filepath": "examples/cms-wordpress/src/utils/fetchGraphQL.ts",
"language": "typescript",
"file_size": 1373,
"cut_index": 524,
"middle_length": 229
} |
rom "next/server";
import type { NextRequest } from "next/server";
import { i18n } from "./i18n-config";
import { match as matchLocale } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
function getLocale(request: NextRequest): string | undefined {
// Negotiator expects plain object so we ... | ltLocale);
return locale;
}
export function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname;
// // `/_next/` and `/api/` are ignored by the watcher, but we need to ignore files in `public` manually.
// // If you have | n.locales);
// Use negotiator and intl-localematcher to get best locale
let languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales,
);
const locale = matchLocale(languages, locales, i18n.defau | {
"filepath": "examples/i18n-routing/middleware.ts",
"language": "typescript",
"file_size": 1891,
"cut_index": 537,
"middle_length": 229
} |
ort { Children } from "react";
import Document, { Html, Head, Main, NextScript } from "next/document";
import { AppRegistry } from "react-native";
import config from "../app.json";
// Force Next-generated DOM elements to fill their parent's height
const normalizeNextElements = `
#__next {
display: flex;
flex-... | tStyleElement(),
];
return { ...page, styles: Children.toArray(styles) };
}
render() {
return (
<Html style={{ height: "100%" }}>
<Head />
<body style={{ height: "100%", overflow: "hidden" }}>
<Main />
| () => Main);
const { getStyleElement } = AppRegistry.getApplication(config.name);
const page = await renderPage();
const styles = [
<style dangerouslySetInnerHTML={{ __html: normalizeNextElements }} />,
ge | {
"filepath": "examples/with-react-native-web/pages/_document.js",
"language": "javascript",
"file_size": 1063,
"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-agilitycms/tailwind.config.js",
"language": "javascript",
"file_size": 791,
"cut_index": 514,
"middle_length": 14
} |
sts } from "./normalize";
import { requireComponentDependencyByName } from "./dependencies";
// Our LIVE API client
const liveClient = agility.getApi({
guid: process.env.AGILITY_CMS_GUID,
apiKey: process.env.AGILITY_CMS_API_FETCH_KEY,
});
// Our PREVIEW API client
const previewClient = agility.getApi({
guid: pr... | this.client = getClient(preview);
}
async getAllPosts(take) {
const data = await this.client.getContentList({
referenceName: `posts`,
languageCode: CMS_LANG,
contentLinkDepth: 1,
take: take, // TODO: Implement pagination
| This client is used by nested components to fetch additional data within `getStaticProps`
export class APIClient {
public preview: any;
public client: any;
constructor({ preview = false }) {
this.preview = preview;
| {
"filepath": "examples/cms-agilitycms/lib/api.ts",
"language": "typescript",
"file_size": 5748,
"cut_index": 716,
"middle_length": 229
} |
"./constants";
//Generates a preview key to compare against
export function generatePreviewKey() {
//the string we want to encode
const str = `-1_${process.env.AGILITY_CMS_SECURITY_KEY}_Preview`;
//build our byte array
let data = [];
for (var i = 0; i < str.length; ++i) {
data.push(str.charCodeAt(i));
... | `/`) {
return {
error: false,
message: null,
slug: `/`,
};
}
const client = getClient(true);
//this is a standard page
const sitemapFlat = await client.getSitemapFlat({
channelName: CMS_CHANNEL,
languageCode: CMS_ | igest("base64");
return previewKey;
}
//Checks that the requested page exists, if not return a 401
export async function validateSlugForPreview({ slug, contentID }) {
//if its for root, allow it and kick out
if (slug === | {
"filepath": "examples/cms-agilitycms/lib/preview.ts",
"language": "typescript",
"file_size": 3045,
"cut_index": 614,
"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-agilitycms/components/alert.tsx",
"language": "tsx",
"file_size": 1206,
"cut_index": 518,
"middle_length": 229
} |
from "next/link";
import Avatar from "../components/avatar";
import Date from "../components/date";
import CoverImage from "../components/cover-image";
export default function HeroPost({
title,
coverImage,
date,
excerpt,
author,
slug,
}) {
return (
<section>
<div className="mb-8 md:mb-16">
... | </h3>
<div className="mb-4 md:mb-0 text-lg">
<Date dateString={date} />
</div>
</div>
{author && (
<div>
<p className="text-lg leading-relaxed mb-4">{excerpt}</p>
<A | -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">
{title}
</Link>
| {
"filepath": "examples/cms-agilitycms/components/hero-post.tsx",
"language": "tsx",
"file_size": 1319,
"cut_index": 524,
"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-agilitycms/components/meta.tsx",
"language": "tsx",
"file_size": 1255,
"cut_index": 524,
"middle_length": 229
} |
ort Header from "./header";
import PostHeader from "./post-header";
import PostBody from "./post-body";
import SectionSeparator from "./section-separator";
import Head from "next/head";
import { CMS_NAME } from "../lib/constants";
export default function PostDetails({ post }) {
return (
<>
<Header />
... | </article>
<SectionSeparator />
</>
);
}
// The data returned here will be send as `props` to the component
PostDetails.getCustomInitialProps = async function ({ client, pageInSitemap }) {
const contentID = pageInSitemap.contentID;
const | rl} />
</Head>
<PostHeader
title={post.title}
coverImage={post.coverImage}
date={post.date}
author={post.author}
/>
<PostBody content={post.content} />
| {
"filepath": "examples/cms-agilitycms/components/post-details.tsx",
"language": "tsx",
"file_size": 1081,
"cut_index": 515,
"middle_length": 229
} |
;
import { useCallback, useEffect, useState } from "react";
import videojs from "video.js";
import "videojs-youtube";
interface PlayerProps {
/**
*
*/
techOrder: string[];
/**
* Is autoplay enabled for this video?
*/
autoplay: boolean;
/**
* Should this video have controls?
*/
controls: ... | t | null>(null);
const onVideo = useCallback((el: HTMLVideoElement) => {
setVideoEl(el);
}, []);
useEffect(() => {
if (videoEl == null) {
return;
}
// our video.js player
const player = videojs(videoEl, props);
return | *
* A simple video player component for displaying videos from external websites.
* @returns A Video.js video player element.
*/
const Player = (props: PlayerProps) => {
const [videoEl, setVideoEl] = useState<HTMLVideoElemen | {
"filepath": "examples/with-videojs/app/_components/Player.tsx",
"language": "tsx",
"file_size": 1303,
"cut_index": 524,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.