next#GetStaticProps TypeScript Examples

The following examples show how to use next#GetStaticProps. 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: showcase.tsx    From pagely with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async () => {
  const sites = await prisma.notionSites.findMany({
    where: {
      inShowcase: true,
    },
    select: {
      siteName: true,
      subdomain: true,
      ogImageUrl: true,
      id: true,
    },
    orderBy: {
      createdAt: 'desc',
    },
  });

  return {
    props: {
      sites,
    },
    revalidate: 1800,
  };
}
Example #2
Source File: [siteId].tsx    From staticshield with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  const siteId = params.siteId as string;

  const res = await fetch(process.env.HARPERDB_URL, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Basic ${process.env.HARPERDB_KEY}`,
    },
    body: JSON.stringify({
      operation: 'sql',
      sql: `SELECT * FROM site_schema.sites where id = "${siteId}"`,
    }),
  });
  const data: HarperDBRecord = (await res.json())[0];

  return {
    props: {
      id: siteId,
      title: data.title || '',
      isLoginBlocked: data.is_login_blocked,
      caption: data.cap,
      logoUrl: data.logo_url || '',
    },
  };
}
Example #3
Source File: [slug].tsx    From BloggerWeb with GNU General Public License v3.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  const postFilePath = path.join(POSTS_PATH, `${params.slug}.mdx`);
  const source = fs.readFileSync(postFilePath);

  const { content, data } = matter(source);

  const mdxSource = await renderToString(content, {
    components,
    // Optionally pass remark/rehype plugins
    mdxOptions: {
      remarkPlugins: [require('remark-code-titles')],
      rehypePlugins: [mdxPrism, rehypeSlug, rehypeAutolinkHeadings],
    },
    scope: data,
  });

  return {
    props: {
      source: mdxSource,
      frontMatter: data,
    },
  };
}
Example #4
Source File: [carId].tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async (context) => {
  const carId = context.params.carId as string;
  const car = await api.getCar(carId);
  console.log(`Fetch car: ${JSON.stringify(car, null, 2)}`);

  return {
    props: {
      car,
    },
  };
}
Example #5
Source File: [authorSlug].tsx    From norfolkdevelopers-website with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  return {
    props: {
      // @ts-ignore
      posts: getAuthors()[params.authorSlug],
      // @ts-ignore
      slug: params.authorSlug,
    },
  };
}
Example #6
Source File: [[...slug]].tsx    From graphql-mesh with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = ctx => {
  return MDXProps(
    ({ readMarkdownFile, getArrayParam }) => {
      return readMarkdownFile('docs/', getArrayParam('slug'), { importPartialMarkdown: true });
    },
    ctx,
    { getRoutes }
  );
}
Example #7
Source File: [province].tsx    From posso-uscire with GNU General Public License v3.0 6 votes vote down vote up
getStaticProps: GetStaticProps<{
  rules: any[];
  province: Province;
  buildTime: number;
}> = async ({ params }) => {
  const { province } = params;
  const selectedProvince = italianRegions.find((p) => p.urlName === province);
  const restrictions = getActiveRestrictions(selectedProvince);
  return {
    props: {
      restrictions,
      province: selectedProvince,
      buildTime: Date.now(),
    },
  };
}
Example #8
Source File: index.tsx    From website with Apache License 2.0 6 votes vote down vote up
getStaticProps: GetStaticProps<Props> = async function () {
	const pinnedRepos = await fetch(
		'https://gh-pinned-repos.egoist.sh/?username=alii',
	).then(async response => response.json() as Promise<PinnedRepo[]>);

	const lanyard = await fetch(
		`https://api.lanyard.rest/v1/users/${DISCORD_ID}`,
	);

	const lanyardBody = (await lanyard.json()) as LanyardResponse;

	if ('error' in lanyardBody) {
		throw new LanyardError(lanyard.status, lanyardBody.error.message);
	}

	return {
		props: {pinnedRepos, lanyard: lanyardBody.data},
		revalidate: 120,
	};
}
Example #9
Source File: [id].tsx    From my-next.js-starter with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async (props) => {
  try {
    const film = await getFilm(props.params?.id as string);

    return { props: { film } };
  } catch (err: any) {
    return { props: { errors: err.message } };
  }
}
Example #10
Source File: [slug].tsx    From aljoseph.co with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async (context) => {
	const post = await getPostBySlug(context.params.slug);
	const tweets = await getTweets(post.tweetIDs);
	const { prevPage, nextPage } = getPagination(context.params.slug);

	return {
		props: {
			post,
			tweets,
			pagination: {
				prevPage,
				nextPage
			}
		}
	};
}
Example #11
Source File: [id].tsx    From dendron with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #12
Source File: packs.tsx    From bedrock-dot-dev with GNU General Public License v3.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ locale: localeVal }) => {
  const locale = getLocale(localeVal)

  const s3 = new S3({
    'accessKeyId': process.env.AWS_ACCESS_KEY_ID_BEDROCK,
    'secretAccessKey': process.env.AWS_SECRET_ACCESS_KEY_BEDROCK,
    'region': 'us-east-1',
  })

  let versions: PackVersions = {}
  let paths: string[] = []

  try {
    const objects = await s3.listObjectsV2({ Bucket: process.env.AWS_BUCKET_NAME_BEDROCK || '' }).promise()
    if (objects.Contents)
      paths = objects.Contents.filter(c => c.Key && c.Key?.endsWith('.zip')).map(c => c.Key!)
  } catch (e) {
    Log.error('Could not list items from bucket!')
  }

  for (let path of paths) {
    const [ folder, name ] = path.split('/')
    if (folder && name) {
      const version = name.replace('.zip', '')
      if (!versions[version]) versions[version] = [false, false]
      if (folder === 'behaviours') versions[version][0] = true
      if (folder === 'resources') versions[version][1] = true
    }
  }

  return { props: { versions, ...await serverSideTranslations(locale, ['common']) } }
}
Example #13
Source File: [slug].tsx    From dhafit.xyz with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async (ctx) => {
  const { params } = ctx;
  const { data, content } = getBlogBySlug(params?.slug);
  const mdxPrism = require("mdx-prism");
  const mdxSource = await serialize(content, {
    mdxOptions: {
      rehypePlugins: [mdxPrism],
    },
  });
  return {
    props: {
      ...data,
      mdxSource,
    },
  };
}
Example #14
Source File: api-docs.tsx    From crypto-fees with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async () => {
  const lastWeekData = await getLastWeek();
  const lastWeek = {
    success: true,
    protocols: lastWeekData.sort((a: any, b: any) => b.fees[0].fee - a.fees[0].fee),
  };
  const protocols = getIDs().map((id: string) => ({ id, ...getMetadata(id) }));

  return { props: { lastWeek, protocols }, revalidate: 60 * 10 };
}
Example #15
Source File: index.tsx    From roamjs-com with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps<Props> = () => {
  const { contributors } = JSON.parse(
    fs.readFileSync("./thankyou.json").toString()
  );
  return Promise.resolve({
    props: {
      recurring: RECURRING.map((title) => ({ ...contributors[title], title })),
      oneTime: ONE_TIME.map((title) => ({ ...contributors[title], title })),
    },
  });
}
Example #16
Source File: [category].tsx    From frontend with Apache License 2.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ locale, params }) => {
  const applications: Appstream[] = await fetchCategory(
    params.category as keyof typeof Category
  )

  return {
    props: {
      ...(await serverSideTranslations(locale, ['common'])),
      applications,
    },
    revalidate: 3600,
  }
}
Example #17
Source File: index.tsx    From ultimate-saas-ts with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps<Props> = async (context) => {
  const products = await prisma?.product.findMany({
    where: {
      active: true,
    },
    include: {
      prices: {
        where: {
          active: true,
        },
      },
    },
  });

  return {
    props: {
      products,
    },
  };
}
Example #18
Source File: [slug].tsx    From podcastr with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async (ctx) => {
  const { slug } = ctx.params

  const { data } = await api.get(`/episodes/${slug}`)

  const episode = {
    id: data.id,
    title: data.title,
    thumbnail: data.thumbnail,
    members: data.members,
    publishedAt: format(parseISO(data.published_at), 'd MMM yy', { locale: ptBR }),
    duration: Number(data.file.duration),
    durationAsString: convertDurationToTimeString(Number(data.file.duration)),
    description: data.description,
    url: data.file.url
  }
  
  return {
    props: {
      episode,
    },
    revalidate: 60 * 60 * 24, // 24 hours
  }
}
Example #19
Source File: [slug].tsx    From website with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({
  params,
  preview = false,
}) => {
  const settings = await getSettings(preview);
  const data = await getDocBySlug(params.slug as string, preview);

  return {
    props: { data, preview, settings },
    revalidate: 1,
  };
}
Example #20
Source File: [[...pathParts]].tsx    From next-translate-routes with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps<
  { date: string; type: string; pathList: string[] },
  { type: string; pathParts: string[] }
> = ({ params }) => ({
  props: {
    date: new Date().toISOString(),
    type: params.type,
    pathList: params.pathParts?.map((pathPart) => `Part ${pathPart}`) || [],
  },
})
Example #21
Source File: about.tsx    From next-sitemap with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ locale }) => {
  if (!['en-US', 'en-NL'].includes(locale)) {
    return {
      notFound: true,
    }
  }

  return {
    props: {},
  }
}
Example #22
Source File: about.tsx    From jeffjadulco.com with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps = async () => {
  let spotify:
    | SpotifyCurrentTrack
    | SpotifyRecentTracks = await getCurrentlyPlaying()
  if (spotify === null) {
    spotify = await getRecentlyPlayed()
  }

  const letterboxd = await getRecentMovies()
  const steam = await getRecentGames()
  const notion = await getDoingNow()
  return {
    props: {
      spotify,
      letterboxd,
      steam,
      notion,
    },
    revalidate: 60,
  }
}
Example #23
Source File: about.tsx    From portfolio with MIT License 6 votes vote down vote up
getStaticProps: GetStaticProps<{
  authorDetails: { mdxSource: string; frontMatter: AuthorFrontMatter };
}> = async () => {
  const authorDetails = await getFileBySlug<AuthorFrontMatter>('authors', [
    'default',
  ]);
  const { mdxSource, frontMatter } = authorDetails;
  return { props: { authorDetails: { mdxSource, frontMatter } } };
}
Example #24
Source File: guidelines.tsx    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
getStaticProps: GetStaticProps<GuidelinesProps> = async () => {
	const res = await fetch(SpecialEndPoints.Github.Content('koreanbots', 'terms', 'guidelines.md'))
	const json = await res.json()
	return {
		props: {
			content: Buffer.from(json.content, 'base64').toString('utf-8')
		}
	}
}
Example #25
Source File: license.tsx    From lucide with ISC License 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  const doc: string = await fs.readFile(resolve('../LICENSE'), 'utf-8');

  const licenseText = doc
    .split(/\n{2,}/)
    .map(paragraph => paragraph.split('\n').join(' ').trim())
    .filter(Boolean);

  return { props: { licenseText } };
}
Example #26
Source File: [slug].tsx    From ksana.in with Apache License 2.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  const slugParams: string = params ? String(params.slug) : ''
  const post: IPost = await getPostBySlug(slugParams)

  return {
    props: { post },
    revalidate: 3
  }
}
Example #27
Source File: translation.ts    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
export function withStaticTranslation(gsp: GetStaticProps): GetStaticProps {
  return async (ctx) => {
    const ssp = await gsp(ctx);
    ssp.revalidate = 60 * 60;
    const locale = ctx.locale;
    if (!locale) {
      return ssp;
    }
    const translation = (await import(`../locales/${ctx.locale}/messages`))
      .messages;
    if ('props' in ssp) {
      return { ...ssp, props: { ...ssp.props, translation } };
    }
    return ssp;
  };
}
Example #28
Source File: [to].tsx    From videotranscode.space with Apache License 2.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async ({ params }) => {
  const to = params?.to as string | undefined

  const splitArr = to?.split('-to-')

  const from = splitArr && splitArr.length > 1 ? splitArr[0] : null

  const splitTo = splitArr?.pop()

  return { props: { to: splitTo, from: from } }
}
Example #29
Source File: index.tsx    From ui with GNU Affero General Public License v3.0 6 votes vote down vote up
getStaticProps: GetStaticProps = async () => {
  // just to be conforming with eslint
  await Promise.resolve()

  return {
    revalidate: 10,
    props: {},
  }
}