next#GetStaticPropsContext TypeScript Examples
The following examples show how to use
next#GetStaticPropsContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: [[...path]].tsx From nextjs-shopify with MIT License | 6 votes |
export async function getStaticProps({
params,
locale,
}: GetStaticPropsContext<{ path: string[] }>) {
const page = await resolveBuilderContent('page', {
locale,
urlPath: '/' + (params?.path?.join('/') || ''),
})
return {
props: {
page,
locale,
...(await getLayoutProps()),
},
// Next.js will attempt to re-generate the page:
// - When a request comes in
// - At most once every 5 seconds
revalidate: 5,
}
}
Example #2
Source File: wishlist.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ config, preview })
return {
props: { ...defaultPageProps, pages },
}
}
Example #3
Source File: search.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ config, preview })
const { categories, brands } = await getSiteInfo({ config, preview })
return {
props: { pages, categories, brands },
}
}
Example #4
Source File: profile.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ config, preview })
return {
props: { pages },
}
}
Example #5
Source File: [slug].tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
params,
locale,
preview,
}: GetStaticPropsContext<{ slug: string }>) {
const config = getConfig({ locale })
let story = {}
const { pages } = await getAllPages({ config, preview })
const { product } = await getProduct({
variables: { slug: params!.slug },
config,
preview,
})
const sbParams = {
version: "draft"
}
try {
const { data } = await Storyblok.get(`cdn/stories/product/${params!.slug}`, sbParams)
if(data.story) story = data.story
} catch(e) {
console.error(`Product ${params!.slug} doesn't exist in Storyblok`)
}
if (!product) {
throw new Error(`Product with slug '${params!.slug}' not found`)
}
return {
props: { pages, product, story },
revalidate: 200,
}
}
Example #6
Source File: orders.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ config, preview })
return {
props: { pages },
}
}
Example #7
Source File: index.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const sbParams = {
version: preview ? "draft" : "published"
}
const { data: { story }} = await Storyblok.get('cdn/stories/home', sbParams)
const copyOfStory = Object.assign({}, story)
const fullProducts = await getDetailsFromStory({ story, config, preview })
copyOfStory.content = fullProducts
return {
props: {
story: copyOfStory,
},
revalidate: 14400,
}
}
Example #8
Source File: cart.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ config, preview })
return {
props: { pages },
}
}
Example #9
Source File: blog.tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
locale,
}: GetStaticPropsContext) {
const config = getConfig({ locale })
const sbParams = {
version: preview ? "draft" : "published"
}
const { data: { story }} = await Storyblok.get('cdn/stories/blog', sbParams)
const { pages } = await getAllPages({ config, preview })
return {
props: {
story,
pages,
},
revalidate: 14400,
}
}
Example #10
Source File: [...pages].tsx From nextjs-bigcommerce-starter with MIT License | 6 votes |
export async function getStaticProps({
preview,
params,
locale,
}: GetStaticPropsContext<{ pages: string[] }>) {
const config = getConfig({ locale })
const { pages } = await getAllPages({ preview, config })
const path = params?.pages.join('/')
const slug = locale ? `${locale}/${path}` : path
const pageItem = pages.find((p) => (p.url ? getSlug(p.url) === slug : false))
const data =
pageItem &&
(await getPage({ variables: { id: pageItem.id! }, config, preview }))
const page = data?.page
if (!page) {
// We throw to make sure this fails at build time as this is never expected to happen
throw new Error(`Page with slug '${slug}' not found`)
}
return {
props: { ...defaultPageProps, pages, page },
revalidate: 60 * 60, // Every hour
}
}
Example #11
Source File: get-nodes.ts From next-mdx with MIT License | 6 votes |
export async function getNode<T extends Node>(
sourceName: string,
context: string | GetStaticPropsContext<NodeJS.Dict<string[]>>
): Promise<T> {
const files = await getFiles(sourceName)
if (!files.length) return null
const slug =
typeof context === "string"
? context
: context.params.slug
? context.params.slug.join("/")
: ""
const [file] = files.filter((file) => file.slug === slug)
if (!file) return null
const node = await buildNodeFromFile(file)
return <T>{
...node,
relationships: await getNodeRelationships(node),
}
}
Example #12
Source File: get-nodes.ts From next-mdx with MIT License | 6 votes |
export async function getMdxNode<T extends MdxNode>(
sourceName: string,
context: string | GetStaticPropsContext<NodeJS.Dict<string[]>>,
params?: MdxParams
): Promise<T> {
if (!context || (typeof context !== "string" && !context.params?.slug)) {
new Error(`slug params missing from context`)
}
const node = await getNode(sourceName, context)
if (!node) return null
return <T>{
...node,
mdx: await renderNodeMdx(node, params),
}
}
Example #13
Source File: index.tsx From oxen-website with GNU General Public License v3.0 | 6 votes |
getStaticProps: GetStaticProps = async (
context: GetStaticPropsContext,
) => {
if (process.env.NEXT_PUBLIC_SITE_ENV !== 'development') {
const cms = new CmsApi();
const posts: IPost[] = [];
let page = 1;
let foundAllPosts = false;
// Contentful only allows 100 at a time
while (!foundAllPosts) {
const { entries: _posts } = await cms.fetchBlogEntries(100, page);
if (_posts.length === 0) {
foundAllPosts = true;
continue;
}
posts.push(..._posts);
page++;
}
generateRSSFeed(posts);
}
return {
props: {},
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
}
Example #14
Source File: faq.tsx From oxen-website with GNU General Public License v3.0 | 6 votes |
getStaticProps: GetStaticProps = async (
context: GetStaticPropsContext,
) => {
const cms = new CmsApi();
const { entries: faqItems, total } = await cms.fetchFAQItems();
return {
props: {
faqItems,
total,
},
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
}
Example #15
Source File: makeContextObject.ts From next-page-tester with MIT License | 6 votes |
export function makeStaticPropsContext({
pageObject,
}: {
pageObject: FoundPageObject;
}): GetStaticPropsContext<typeof pageObject.params> {
const { params } = pageObject;
const { locale, locales, defaultLocale } = getLocales({ pageObject });
// @TODO complete ctx object
// https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation
return {
params: { ...params },
locale,
locales,
defaultLocale,
};
}
Example #16
Source File: [value].tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export async function getStaticProps({
params,
}: GetStaticPropsContext<KeywordParams>): Promise<
GetStaticPropsResult<KeywordPageProps>
> {
const { value } = params;
return {
props: {
keyword: value,
},
revalidate: 60,
};
}
Example #17
Source File: [slug].tsx From next-saas-starter with MIT License | 6 votes |
export async function getStaticProps({ params }: GetStaticPropsContext<{ slug: string }>) {
const { slug } = params as { slug: string };
const variables = { relativePath: `${slug}.mdx` };
const query = `
query BlogPostQuery($relativePath: String!) {
getPostsDocument(relativePath: $relativePath) {
data {
title
description
date
tags
imageUrl
body
}
}
}
`;
const data = (await staticRequest({
query: query,
variables: variables,
})) as { getPostsDocument: PostsDocument };
return {
props: { slug, variables, query, data },
};
}
Example #18
Source File: [handle].tsx From nextjs-shopify with MIT License | 6 votes |
export async function getStaticProps({
params,
locale,
}: GetStaticPropsContext<{ handle: string }>) {
const collection = await getCollection(shopifyConfig, {
handle: params?.handle,
})
const page = await resolveBuilderContent(builderModel, {
collectionHandle: params?.handle,
locale,
})
return {
notFound: !page,
props: {
page: page || null,
collection: collection || null,
...(await getLayoutProps()),
},
}
}
Example #19
Source File: [handle].tsx From nextjs-shopify with MIT License | 6 votes |
export async function getStaticProps({
params,
locale,
}: GetStaticPropsContext<{ handle: string }>) {
const product = await getProduct(shopifyConfig, {
handle: params?.handle,
})
const page = await resolveBuilderContent(builderModel, {
productHandle: params?.handle,
locale,
})
return {
notFound: !page ,
props: {
page: page || null,
product: product || null,
...(await getLayoutProps()),
},
}
}
Example #20
Source File: [...slug].tsx From thvu-blog with MIT License | 6 votes |
export async function getStaticProps({ params }: GetStaticPropsContext) {
const allPosts = await getAllFilesFrontMatter("blog");
const postIndex = allPosts.findIndex(
(post) => formatSlug(post.slug) === (params?.slug as string[]).join("/")
);
const prev = allPosts[postIndex + 1] || null;
const next = allPosts[postIndex - 1] || null;
const post = await getFileBySlug("blog", params?.slug as string);
// rss
const rss = generateRss(allPosts);
fs.writeFileSync("./public/feed.xml", rss);
return { props: { post, prev, next } };
}
Example #21
Source File: [tag].tsx From thvu-blog with MIT License | 6 votes |
export async function getStaticProps({ params }: GetStaticPropsContext) {
const allPosts = await getAllFilesFrontMatter("blog");
const tag = params?.tag as string;
const filteredPosts = allPosts.filter(
(post) => post.draft !== true && post.tags.map((t) => kebabCase(t)).includes(tag)
);
// rss
const rss = generateRss(filteredPosts, `tags/${tag}/feed.xml`);
const rssPath = path.join(root, "public", "tags", tag);
fs.mkdirSync(rssPath, { recursive: true });
fs.writeFileSync(path.join(rssPath, "feed.xml"), rss);
return { props: { posts: filteredPosts, tag } };
}
Example #22
Source File: index.tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export async function getStaticProps({
params,
}: GetStaticPropsContext<ProfileParams>): Promise<
GetStaticPropsResult<Omit<ProfileLayoutProps, 'children'>>
> {
const { userId } = params;
try {
const profile = await getProfileSSR(userId);
return {
props: {
profile,
},
revalidate: 60,
};
} catch (err) {
if ('message' in err && err.message === 'not found') {
return {
props: { profile: null },
revalidate: 60,
};
}
throw err;
}
}
Example #23
Source File: [...slug].tsx From website with MIT License | 6 votes |
getStaticProps = async ({
params,
preview,
}: GetStaticPropsContext) => {
const settings = await getSettings(preview);
const [base, ...rest] = params.slug as string[];
const path = [`/${base}`].concat(rest).join('/');
const page = await getPageByPath(path, preview);
if (typeof page.title === 'undefined') {
return {
props: {} as never,
notFound: true,
};
}
return {
props: {
settings,
page,
},
revalidate: 1,
};
}
Example #24
Source File: [id].tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export async function getStaticProps({
params,
}: GetStaticPropsContext<PostParams>): Promise<GetStaticPropsResult<Props>> {
const { id } = params;
try {
const postData = await request<PostData>(
`${apiUrl}/graphql`,
POST_BY_ID_STATIC_FIELDS_QUERY,
{ id },
);
return {
props: {
id,
postData,
},
revalidate: 60,
};
} catch (err) {
const clientError = err as ClientError;
if (clientError?.response?.errors?.[0]?.extensions?.code === 'NOT_FOUND') {
return {
props: { id: null },
revalidate: 60,
};
}
throw err;
}
}
Example #25
Source File: [source].tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export async function getStaticProps({
params,
}: GetStaticPropsContext<SourcePageParams>): Promise<
GetStaticPropsResult<SourcePageProps>
> {
try {
const res = await request<SourceData>(`${apiUrl}/graphql`, SOURCE_QUERY, {
id: params.source,
});
return {
props: {
source: res.source,
},
revalidate: 60,
};
} catch (err) {
if (err?.response?.errors?.[0].extensions.code === 'NOT_FOUND') {
return {
props: {
source: null,
},
revalidate: 60,
};
}
throw err;
}
}
Example #26
Source File: [tag].tsx From apps with GNU Affero General Public License v3.0 | 6 votes |
export function getStaticProps({
params,
}: GetStaticPropsContext<TagPageParams>): GetStaticPropsResult<TagPageProps> {
return {
props: {
tag: params.tag,
},
};
}
Example #27
Source File: [id].tsx From dendron with GNU Affero General Public License v3.0 | 6 votes |
getStaticProps: GetStaticProps = async (
context: GetStaticPropsContext
) => {
const { params } = context;
if (!params) {
throw Error("params required");
}
const id = params["id"];
if (!_.isString(id)) {
throw Error("id required");
}
try {
const [body, note] = await Promise.all([getNoteBody(id), getNoteMeta(id)]);
const noteData = getNotes();
const customHeadContent: string | null = await getCustomHead();
const { notes, noteIndex } = noteData;
const collectionChildren = note.custom?.has_collection
? prepChildrenForCollection(note, notes, noteIndex)
: null;
const props: DendronNotePageProps = {
note,
body,
noteIndex,
collectionChildren,
customHeadContent,
config: await getConfig(),
};
return {
props,
};
} catch (err) {
// eslint-disable-next-line no-console
console.log(error2PlainObject(err as DendronError));
throw err;
}
}
Example #28
Source File: getStaticPropsUtil.tsx From dendron with GNU Affero General Public License v3.0 | 6 votes |
getStaticProps: GetStaticProps = async (
context: GetStaticPropsContext
) => {
const { noteIndex: note, notes } = getNotes();
const body = await getNoteBody(note.id);
const config = await getConfig();
const customHeadContent: string | null = await getCustomHead();
const collectionChildren = note.custom?.has_collection
? prepChildrenForCollection(note, notes, note)
: null;
const props: DendronNotePageProps = {
body,
note,
config,
customHeadContent,
noteIndex: note,
collectionChildren,
};
return {
props,
};
}
Example #29
Source File: [...slug].tsx From oxen-website with GNU General Public License v3.0 | 5 votes |
getStaticProps: GetStaticProps = async (
context: GetStaticPropsContext,
) => {
console.log(
`Building Results for tag "%c${context.params.slug[0]}" page ${
context.params.slug && context.params.slug[1]
? context.params.slug[1]
: ''
}`,
'color: purple;',
);
const cms = new CmsApi();
const tag = String(context.params.slug[0] ?? '') ?? null;
const page = Number(context.params.slug[1] ?? 1);
try {
const {
entries: tagPosts = [],
total: tagTotalPosts,
} = await cms.fetchBlogEntriesByTag(
tag,
CMS.BLOG_RESULTS_PER_PAGE_TAGGED,
page,
);
const { entries: posts, total: totalPosts } = await cms.fetchBlogEntries(
CMS.BLOG_RESULTS_PER_PAGE_TAGGED,
);
const pageCount = Math.ceil(
tagTotalPosts / CMS.BLOG_RESULTS_PER_PAGE_TAGGED,
);
if (page > pageCount && page > 1) {
throw 'Page results exceeded!';
}
return {
props: {
posts,
pageCount,
currentPage: page,
tag,
tagPosts,
},
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
} catch (err) {
console.error(err);
return {
notFound: true,
revalidate: CMS.CONTENT_REVALIDATE_RATE,
};
}
}