next#GetServerSidePropsContext TypeScript Examples
The following examples show how to use
next#GetServerSidePropsContext.
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: [...slug].tsx From oxen-website with GNU General Public License v3.0 | 6 votes |
getServerSideProps: GetServerSideProps = async (
context: GetServerSidePropsContext,
) => {
const slug = context.params?.slug.toString().split(',').join('/') ?? '';
const id = unslugify(slug);
console.log(`Loading Preview %c${slug}`, 'color: purple;');
try {
const cms = new CmsApi();
let page: ISplitPage | IPost;
if (SideMenuItem[id]) {
page = await cms.fetchEntryPreview(SideMenuItem[id], 'splitPage');
} else {
let query = slug;
if (slug.indexOf('blog/') >= 0) query = slug.split('blog/')[1];
page = await cms.fetchEntryPreview(query, 'post');
// embedded links in post body need metadata for preview
page.body = await generateLinkMeta(page.body);
}
console.log(`Built Preview %c${slug}`, 'color: purple;');
return {
props: {
page,
slug,
},
};
} catch (err) {
console.error(err);
return {
notFound: true,
};
}
}
Example #2
Source File: index.tsx From Demae with MIT License | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext<{
providerID: string
}>) {
const { params } = context
if (!params) return { props: {} }
const provider = await Provider.get<Provider>(params.providerID)
if (!provider) return { props: {} }
const data = provider.data()
const { name, caption, description } = data
const title = `${name} ${caption}`
const url = context.req.url
const image = provider.thumbnailImageURL() || "" // TODO: Default Image
const og: OpenGraph.Metadata<"website"> = {
type: "website",
title,
image,
description,
url: `${process.env.HOST}${url}`,
}
const site = provider.sns?.twitter
const creator = site
let twitter = {
card: "summary_large_image",
title,
image,
description,
url: `${process.env.HOST}${url}`,
}
if (site) twitter["site"] = site
if (creator) twitter["creator"] = creator
return {
props: { title, description, url, og, twitter }
}
}
Example #3
Source File: dashboard.tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Error object to return if outside conditions fails
const error = { props: { authorized: false, level: AccessLevel.STANDARD, info: null, error: false } };
// Get the token from cookies
const tokenCookie = ctx.req.cookies.token;
if (!tokenCookie) {
return error;
}
// Parse the token
const token = JSON.parse(tokenCookie).token as string;
// Check if valid token and compare with database
const authRes = await getAuthInfo(token);
if (authRes.status !== 200 || !authRes.data.loggedIn) {
return error;
}
// Token is valid, get user info
const userRes = await getUserInfo(token);
if (userRes.status !== 200) {
return { props: { authorized: true, level: AccessLevel.STANDARD, info: null, error: false } };
}
// Check to see if user is an admin and show button if so
return {
props: {
authorized: true,
level: authRes.data.level,
info: userRes.data,
error: false,
},
};
}
Example #4
Source File: index.tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Get the token from cookies
const token = ctx.req.cookies.token;
if (token === undefined) return { props: { authorized: false } };
// Check if valid token and compare with database
const res = await getAuthInfo(token);
if (res.status === 200 && res.data.loggedIn) {
return { props: { authorized: true } };
} else {
return { props: { authorized: false, error: res.status !== 200 } };
}
}
Example #5
Source File: signin.tsx From thvu-blog with MIT License | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext) {
const session = await getServerSession(context, authOptions);
if (session) {
return {
redirect: {
permanent: false,
destination: "/",
},
};
}
const providers = await getProviders();
return {
props: { providers },
};
}
Example #6
Source File: locales.ts From compose-starter-helpcenter-nextjs with MIT License | 6 votes |
withLocale = (
fn: (
locale: Locale,
context: GetServerSidePropsContext
) => Promise<GetServerSidePropsResult<Record<string, unknown>>>
) => {
return (context: GetServerSidePropsContext) => {
const locale = getLocale(context.params.locale);
switch (locale) {
case UnknownLocale:
context.res.writeHead(302, { Location: '/' }).end();
break;
case undefined:
context.res.statusCode = 404;
break;
default:
return fn(locale, context);
}
};
}
Example #7
Source File: response.ts From next-sitemap with MIT License | 6 votes |
withXMLResponse = (
ctx: GetServerSidePropsContext,
content: string
) => {
if (ctx?.res) {
const { res } = ctx
// Set header
res.setHeader('Content-Type', 'text/xml')
// Write the sitemap context to resonse
res.write(content)
// End response
res.end()
}
// Empty props
return {
props: {},
}
}
Example #8
Source File: sitemap-index.ts From next-sitemap with MIT License | 6 votes |
getServerSideSitemapIndex = async (
ctx: GetServerSidePropsContext,
sitemaps: string[]
) => {
// Generate index sitemap xml content
const indexContents = new SitemapBuilder().buildSitemapIndexXml(sitemaps)
// Return response
return withXMLResponse(ctx, indexContents)
}
Example #9
Source File: sitemap.ts From next-sitemap with MIT License | 6 votes |
getServerSideSitemap = async (
ctx: GetServerSidePropsContext,
fields: ISitemapField[]
) => {
// Generate sitemap xml
const contents = new SitemapBuilder().buildSitemapXml(fields)
return withXMLResponse(ctx, contents)
}
Example #10
Source File: makeContextObject.ts From next-page-tester with MIT License | 6 votes |
export function makeGetServerSidePropsContext({
pageObject,
options,
}: {
pageObject: FoundPageObject;
options: ExtendedOptions;
}): GetServerSidePropsContext<typeof pageObject.params> {
const { req: reqMocker, res: resMocker, previousRoute } = options;
const { params, query, resolvedUrl } = pageObject;
const { req, res } = makeHttpObjects({
pageObject,
reqMocker,
resMocker,
refererRoute: previousRoute,
});
const { locale, locales, defaultLocale } = getLocales({ pageObject });
// parsed "cookies" are only available in "getServerSideProps" data fetching method
// https://github.com/vercel/next.js/pull/19724/files#diff-f1cccfe490138be7dae0d63562f6a2834af92d21130e0ff10d6de7ad30613f6bR132
if (req.headers.cookie) {
req.cookies = parse(req.headers.cookie);
}
// @TODO complete ctx object
// https://nextjs.org/docs/basic-features/data-fetching#getserversideprops-server-side-rendering
return {
params: { ...params },
query: { ...query },
resolvedUrl,
req,
res,
locale,
locales,
defaultLocale,
};
}
Example #11
Source File: admin.tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Get the token from cookies
const tokenCookie = ctx.req.cookies.token;
if (tokenCookie === undefined) return { props: { authorized: false, error: false } };
const token = JSON.parse(tokenCookie).token as string;
// Check if valid token and compare with database
const res = await getAuthInfo(token);
if (res.status !== 200) return { props: { authorized: false, error: true } };
// If there is no issue with the authorization, authorize user!
return { props: { authorized: res.data.loggedIn && res.data.level === AccessLevel.ADMIN, error: false } };
}
Example #12
Source File: index.ts From po8klasie with GNU General Public License v3.0 | 6 votes |
getServerSideProps = async (
context: GetServerSidePropsContext<ProjectIndexPageParams>,
): Promise<GetServerSidePropsResult<{ PROJECT: Partial<ProjectConfig> }>> => {
const projectID = context?.params?.projectID;
if (!projectID) {
return {
notFound: true,
};
}
return {
redirect: {
destination: `/${projectID}/search`,
permanent: false,
},
};
}
Example #13
Source File: [schoolID].tsx From po8klasie with GNU General Public License v3.0 | 6 votes |
getServerSideProps = async (
context: GetServerSidePropsContext<SchoolPageParams>,
): Promise<
GetServerSidePropsResult<{ PROJECT: Partial<ProjectConfig>; school: RailsApiSchool }>
> => {
const schoolID = context?.params?.schoolID;
const projectID = context?.params?.projectID;
if (!schoolID || !projectID)
return {
notFound: true,
};
const fetcher = await import('../../../api/railsAPI/fetcher').then((m) => m.default);
const school = (await fetcher(`/institutions/${schoolID}`)) as RailsApiSchool;
if (!school.id) return { notFound: true };
return {
props: {
PROJECT: await getProjectConfigProps(['appearance', 'schoolInfo'], projectID),
school,
},
};
}
Example #14
Source File: search.tsx From po8klasie with GNU General Public License v3.0 | 6 votes |
getServerSideProps = async (
context: GetServerSidePropsContext<SearchPageParams>,
): Promise<GetServerSidePropsResult<{ PROJECT: Partial<ProjectConfig> }>> => {
const projectID = context?.params?.projectID;
if (!projectID)
return {
notFound: true,
};
return {
props: {
PROJECT: await getProjectConfigProps(['appearance', 'searchView'], projectID),
},
};
}
Example #15
Source File: index.tsx From po8klasie with GNU General Public License v3.0 | 6 votes |
getServerSideProps = async ({
locale,
}: GetServerSidePropsContext): Promise<GetServerSidePropsResult<any>> => ({
props: {
...(await serverSideTranslations(locale as string, ['landing'])),
projectsList: Object.values(projectConfigs).map(({ projectID, appearance }) => ({
projectID,
appName: appearance.appName,
})),
},
})
Example #16
Source File: securedProps.ts From frontend with MIT License | 6 votes |
securedProps: (
ctx: GetServerSidePropsContext,
returnUrl?: string,
) => Promise<GetServerSidePropsResult<Session>> = async (ctx, returnUrl?: string) => {
const session = await getSession(ctx)
let url = returnUrl ?? ctx.req.url ?? ''
if (url.startsWith('/_next') || url.startsWith('/_error')) url = '/'
if (!session) {
return {
redirect: {
destination: `${routes.login}?callbackUrl=${encodeURIComponent(url)}`,
permanent: false,
},
}
}
return {
props: session,
}
}
Example #17
Source File: securedProps.ts From frontend with MIT License | 6 votes |
securedAdminProps: (
namespaces?: string[],
resolveEndpoint?: (ctx: GetServerSidePropsContext) => string,
) => GetServerSideProps<Session> = (namespaces, resolveEndpoint) => async (ctx) => {
const result = securedPropsWithTranslation(namespaces)
const response = await result(ctx)
if ('props' in response) {
const client = new QueryClient()
if (resolveEndpoint) {
const { accessToken } = await response.props
await client.prefetchQuery(resolveEndpoint(ctx), authQueryFnFactory(accessToken))
}
return {
props: {
...response.props,
dehydratedState: dehydrate(client),
},
}
}
return response
}
Example #18
Source File: [slug].tsx From frontend with MIT License | 6 votes |
getServerSideProps: GetServerSideProps = async (ctx: GetServerSidePropsContext) => {
const { slug } = ctx.query
const response = await securedProps(ctx, `/campaigns/donation/${slug}`)
const client = new QueryClient()
await client.prefetchQuery(`/campaign/${slug}`, queryFn)
if ('props' in response) {
return {
props: {
...response.props,
slug,
dehydratedState: dehydrate(client),
...(await serverSideTranslations(ctx.locale ?? 'bg', [
'common',
'auth',
'validation',
'campaigns',
'one-time-donation',
])),
},
}
}
return response
}
Example #19
Source File: me.tsx From genql with MIT License | 6 votes |
export async function getServerSideProps(
ctx: GetServerSidePropsContext,
): Promise<{ props: Props }> {
const { uid } = await getFirebaseDecodedToken(ctx.req)
// console.log('uid', uid)
if (!uid) {
console.log('redirecting to /')
ctx.res.writeHead(302, { Location: '/' }).end()
return
}
const packages = await admin
.firestore()
.collection('packages')
.orderBy('timestamp', 'desc')
.where('user_uid', '==', uid)
.get()
return {
props: {
packages: packages.docs.map((x) => {
const data = x.data()
return {
...data,
url: `https://www.npmjs.com/package/${data?.name}`,
createdAt: (x?.createTime?.toMillis() || 0) / 1000,
}
}) as any,
},
}
}
Example #20
Source File: feed.tsx From 35d-blog with MIT License | 6 votes |
getServerSideProps = async ({ res }: GetServerSidePropsContext) => {
const xml = await generateFeedXml()
res.statusCode = 200
res.setHeader('Cache-Control', 's-maxage=86400, stale-while-revalidate') // 24時間キャッシュする
res.setHeader('Content-Type', 'text/xml')
res.end(xml)
return {
props: {},
}
}
Example #21
Source File: [[...id]].tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const id = ctx.params.id as string;
if (!id) return { props: { volunteering: createVolunteering(), id: null, error: false } };
const volRes = await getVolunteering(id);
const error = volRes.status !== 200;
const volunteering = error ? createVolunteering() : volRes.data;
return {
props: { volunteering, error, id: error ? null : id },
};
}
Example #22
Source File: [id].tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const id = ctx.params.id as string;
const resource = ctx.params.resource as Resource;
console.log('?');
const historyRes = await getHistory(resource, id);
const sortedHistory = historyRes.status === 200 ? historyRes.data.history.sort((a, b) => b.time - a.time) : null;
const error = historyRes.status !== 200;
return {
props: {
historyList: error ? [] : sortedHistory,
name: error ? '' : (historyRes.data.name as string),
error,
resource,
id,
},
};
}
Example #23
Source File: [[...id]].tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const id = ctx.params.id as string;
if (!id) return { props: { event: createEvent(), id: null, error: false } };
const eventRes = await getEvent(id);
const error = eventRes.status !== 200;
const event = error ? createEvent() : eventRes.data;
return {
props: { event, error, id: error ? null : id },
};
}
Example #24
Source File: [[...id]].tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
const id = ctx.params.id as string;
if (!id) return { props: { club: createClub(), id: null, error: false } };
const clubRes = await getClub(id);
const error = clubRes.status !== 200;
const club = error ? createClub() : clubRes.data;
return {
props: { club, error, id: error ? null : id },
};
}
Example #25
Source File: collection.tsx From frames with Mozilla Public License 2.0 | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext) {
const pathname = context.query;
const Media = await import("../server/classes/media").then(m => m.default);
const MiddleWare = await import("../server/classes/middleware").then(m => m.default);
const media = new Media();
const middleware = new MiddleWare();
if (pathname.collectionId || pathname.collectionName) {
const id = pathname.collectionId as string || '' + (await media.findCollection(middleware.convertUrl(pathname.collectionName as string)));
const collection = await media.getCollection(+id);
if (collection) {
const metaTags: MetaTags = {
name: collection.name,
overview: 'See all the media in the ' + collection.name + ' collection.',
link: `/collection=${collection.id}`,
poster: collection.poster,
};
return {
props: {
metaTags,
collection,
},
};
}
}
return {
redirect: {
destination: '/',
permanent: false,
}
}
}
Example #26
Source File: [[...date]].tsx From tams-club-cal with MIT License | 6 votes |
getServerSideProps = async (ctx: GetServerSidePropsContext) => {
// Extract params to get the month to use
const now = parseDateParams(ctx.params.date as string[]);
// Get the reservation for the given week
// and send an error if either fails to retrieve
const reservations = await getReservationList(now.valueOf());
return {
props: {
now: now.valueOf(),
reservationList: reservations.data,
error: reservations.status !== 200,
},
};
}
Example #27
Source File: person.tsx From frames with Mozilla Public License 2.0 | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext) {
const pathname = context.query;
const Media = await import("../server/classes/media").then(m => m.default);
const MiddleWare = await import("../server/classes/middleware").then(m => m.default);
const media = new Media();
const middleware = new MiddleWare();
if (pathname.id || pathname.person) {
const id = pathname.id as string || '' + (await media.findPerson(middleware.convertUrl(pathname.person as string)));
const person = await media.getPerson(+id);
if (person) {
const metaTags: MetaTags = {
name: person.name,
overview: `See all media by ${person.name} available on Frames`,
link: `/person=${person.name.replace(/\s/g, '+')}`,
poster: person.photo
}
return {
props: {
person,
metaTags
}
}
}
}
return {
redirect: {
destination: '/',
permanent: false,
}
}
}
Example #28
Source File: test.tsx From frames with Mozilla Public License 2.0 | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext) {
const MiddleWare = await import("../server/classes/middleware").then(m => m.default);
const Media = await import("../server/classes/media").then(m => m.default);
const trendingData = await new Media().getTrending();
const data = trendingData.map(e => {
const {id, backdrop, type, trailer, logo, name, overview} = e;
return {id, backdrop, type, trailer, logo, name, overview}
}).filter(e => e.logo !== null && e.type === MediaType.MOVIE).slice(0, 10) as Banner[];
const pop = data.pop();
const banner = [pop, ...data];
const middleware = new MiddleWare();
const {context: role} = await middleware.confirmContent<CookiePayload>(context.req.cookies, 'frames-cookie') || {
email: 'unknown', context: Role.GUEST, session: 'unknown', validUntil: 0,
};
if (role !== Role.ADMIN) return {
notFound: true
}
return {
props: {
banner
}
}
}
Example #29
Source File: prod.tsx From frames with Mozilla Public License 2.0 | 6 votes |
export async function getServerSideProps(context: GetServerSidePropsContext) {
const pathname = context.query;
const Media = await import("../server/classes/media").then(m => m.default);
const MiddleWare = await import("../server/classes/middleware").then(m => m.default);
const media = new Media();
const middleware = new MiddleWare();
if (pathname.id || pathname.prod) {
const id = pathname.id as string || '' + (await media.findProductionCompany(middleware.convertUrl(pathname.prod as string)));
const prod = await media.getProductionCompany(id);
if (prod) {
const metaTags: MetaTags = {
name: prod.name,
overview: 'See all the media produced by ' + prod.name,
poster: prod.logo,
link: '/productionCompany=' + prod.name.replace(/\s/g, '+'),
}
return {
props: {
metaTags,
prod,
}
}
}
}
return {
redirect: {
destination: '/',
permanent: false,
}
}
}