next#GetServerSideProps TypeScript Examples

The following examples show how to use next#GetServerSideProps. 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: a.tsx    From next-page-tester with MIT License 7 votes vote down vote up
getServerSideProps: GetServerSideProps<Props> = async (
  context
) => {
  try {
    const { Auth } = withSSRContext(context);
    const user = await Auth.currentAuthenticatedUser();
    return { props: { message: user.username } };
  } catch (error) {
    return { props: { message: error } };
  }
}
Example #2
Source File: index.tsx    From frontend with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<{
  session: Session | null
}> = async (ctx) => {
  const session = await getSession(ctx)
  return {
    props: {
      ...(await serverSideTranslations(ctx.locale ?? 'bg', ['common', 'index', 'campaigns'])),
      session,
    },
  }
}
Example #3
Source File: authenticated.tsx    From next-page-tester with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<Props> = async ({
  req,
}) => {
  return {
    props: {
      reqHeadersCookie: req.headers.cookie,
      reqCookies: req.cookies,
    },
  };
}
Example #4
Source File: [[...path]].tsx    From mui-toolpad with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<ToolpadAppProps> = async (context) => {
  const { loadVersionedDom, findActiveDeployment } = await import('../../../src/server/data');

  const [appId] = asArray(context.query.appId);

  if (!appId) {
    return {
      notFound: true,
    };
  }

  const activeDeployment = await findActiveDeployment(appId);

  if (!activeDeployment) {
    return {
      notFound: true,
    };
  }

  const { version } = activeDeployment;

  const dom = await loadVersionedDom(appId, version);

  return {
    props: {
      appId,
      dom,
      version,
      basename: `/deploy/${appId}`,
    },
  };
}
Example #5
Source File: login.tsx    From frontend with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async (ctx) => {
  const session = await getSession(ctx)
  if (session) {
    return {
      redirect: {
        destination: routes.profile.index,
        permanent: false,
      },
    }
  }
  return {
    props: {
      ...(await serverSideTranslations(ctx.locale ?? 'bg', ['common', 'auth', 'validation'])),
    },
  }
}
Example #6
Source File: [[...pageNumber]].tsx    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
gssp: GetServerSideProps<PageProps> = async ({ res, params }) => {
  const pn = params?.pageNumber;
  let page: number;
  if (!pn) {
    page = 0;
  } else if (Array.isArray(pn) && pn.length === 1 && pn[0]) {
    page = parseInt(pn[0]);
    if (page.toString() !== pn[0] || page <= 0 || page >= 10) {
      return { props: { error: 'Bad page number' } };
    }
  } else {
    return { props: { error: 'Bad page number' } };
  }

  const [puzzlesWithoutConstructor, hasNext] = await paginatedPuzzles(
    page,
    PAGE_SIZE
  );
  const puzzles = await Promise.all(
    puzzlesWithoutConstructor.map(async (p) => ({
      ...p,
      constructorPage: await userIdToPage(p.authorId),
      constructorIsPatron: await isUserPatron(p.authorId),
    }))
  );
  res.setHeader('Cache-Control', 'public, max-age=1800, s-maxage=3600');
  return {
    props: {
      puzzles,
      currentPage: page,
      prevPage: page > 0 ? page - 1 : null,
      nextPage: hasNext && page < 9 ? page + 1 : null,
    },
  };
}
Example #7
Source File: register.tsx    From frontend with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<RegisterPageProps> = async (ctx) => {
  const session = await getSession(ctx)
  if (session) {
    return {
      redirect: {
        destination: routes.profile.index,
        permanent: false,
      },
    }
  }
  return {
    props: {
      ...(await serverSideTranslations(ctx.locale ?? 'bg', ['common', 'auth', 'validation'])),
      providers: await getProviders(),
    },
  }
}
Example #8
Source File: [pageNumber].tsx    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
gssp: GetServerSideProps<PageProps> = async ({ res, params }) => {
  if (!params?.pageNumber || Array.isArray(params.pageNumber)) {
    return { props: { error: 'Bad params' } };
  }

  const page = parseInt(params.pageNumber);
  if (page < 1 || page.toString() !== params.pageNumber || page >= 10) {
    return { props: { error: 'Bad page number' } };
  }
  const [puzzlesWithoutConstructor, hasNext] = await paginatedPuzzles(
    page,
    PAGE_SIZE,
    'f',
    true
  );
  const puzzles = await Promise.all(
    puzzlesWithoutConstructor.map(async (p) => ({
      ...p,
      constructorPage: await userIdToPage(p.authorId),
      constructorIsPatron: await isUserPatron(p.authorId),
    }))
  );
  res.setHeader('Cache-Control', 'public, max-age=1800, s-maxage=3600');
  return {
    props: {
      puzzles,
      currentPage: page,
      prevPage: page > 0 ? page - 1 : null,
      nextPage: hasNext && page < 9 ? page + 1 : null,
    },
  };
}
Example #9
Source File: [id].tsx    From next-crud with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<IProps> = async (ctx) => {
  const user = await fetch(`${process.env.API_URL}/users/${ctx.query.id}`).then(
    (res) => res.json()
  )

  return {
    props: { user },
  }
}
Example #10
Source File: translation.ts    From crosshare with GNU Affero General Public License v3.0 6 votes vote down vote up
export function withTranslation(gssp: GetServerSideProps): GetServerSideProps {
  return async (ctx) => {
    const ssp = await gssp(ctx);
    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 #11
Source File: email-unsubscribe.tsx    From coindrop with GNU General Public License v3.0 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async (context) => {
    try {
        const { query: { token }} = context;
        const [userEmail, emailListId]: [string, EmailListIds] = cryptr.decrypt(token).split(" ");
        const ref = await db()
            .collection('users')
            .where('email', '==', userEmail);
        const usersQuerySnapshot = await ref.get();
        if (usersQuerySnapshot.empty) {
            throw new Error('No matching user e-mail');
        }
        if (usersQuerySnapshot.size > 1) {
            throw new Error('More than one e-mail matched');
        }
        let userDoc;
        usersQuerySnapshot.forEach(userDocTemp => {
            userDoc = userDocTemp;
        });
        const emailListsCurrent = userDoc.data().email_lists;
        const emailListsNew = Array.from(emailListsCurrent);
        emailListsNew.splice(emailListsNew.indexOf(emailListId), 1);
        await userDoc.ref.update({ email_lists: emailListsNew });
        return {
            props: {
                isUnsubscribeSuccessful: true,
                emailListId,
                userEmail,
            },
        };
    } catch (err) {
        console.error(err);
        return {
            props: {
                isUnsubscribeSuccessful: false,
            },
        };
    }
}
Example #12
Source File: join.tsx    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async (ctx) => {
	const data = await get.server.load(ctx.query.id as string)
	if(!data) return { props: {} }
	// // const record = await Bots.updateOne({ _id: data.id, 'inviteMetrix.day': getYYMMDD() }, { $inc: { 'inviteMetrix.$.count': 1 } })
	// if(record.n === 0) await Bots.findByIdAndUpdate(data.id, { $push: { inviteMetrix: { count: 1 } } }, { upsert: true })
	ctx.res.statusCode = 307
	ctx.res.setHeader('Location', DiscordEnpoints.ServerInvite(data.invite))
	return {
		props: {}
	}
}
Example #13
Source File: account.tsx    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<SessionProp> = async (
  ctx,
) => {
  const session = await getSession(ctx as any)

  return {
    props: { session },
  }
}
Example #14
Source File: login.tsx    From next-page-tester with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<Props> = async ({
  req,
}) => {
  return {
    props: {
      reqHeadersCookie: req.headers.cookie,
      reqCookies: req.cookies,
    },
  };
}
Example #15
Source File: chat.tsx    From frontend with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<LoginPageProps> = async (ctx) => {
  return {
    props: {
      ...(await serverSideTranslations(ctx.locale ?? 'bg', ['common', 'auth', 'validation'])),
      csrfToken: '',
      providers: [],
    },
  }
}
Example #16
Source File: index.tsx    From condo with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async ({ query }) => {
    if (propertiesTypes.includes(query.tab as PropertiesType)) {
        return {
            props: {
                tab: query.tab,
            },
        }
    }
    return {
        props: {},
    }
}
Example #17
Source File: [...slug].tsx    From oxen-website with GNU General Public License v3.0 6 votes vote down vote up
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 #18
Source File: securedProps.ts    From frontend with MIT License 6 votes vote down vote up
securedPropsWithTranslation: (
  namespaces?: string[],
  returnUrl?: string,
) => GetServerSideProps<Session> =
  (namespaces = ['common', 'auth', 'validation'], returnUrl) =>
  async (ctx) => {
    const response = await securedProps(ctx, returnUrl)
    if ('props' in response) {
      return {
        props: {
          ...response.props,
          ...(await serverSideTranslations(ctx.locale ?? 'bg', namespaces)),
        },
      }
    }
    return response
  }
Example #19
Source File: [topicId].tsx    From hakka with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<PageProps> = async (
  ctx,
) => {
  const { user } = await getServerSession(ctx.req)
  const topicId = parseInt(ctx.query.topicId as string)
  const graphqlContext = {
    req: ctx.req,
    res: ctx.res,
    user,
  }

  const topic = await prisma.topic.findUnique({
    where: {
      id: topicId,
    },
  })

  if (!topic || topic.hidden) {
    return {
      notFound: true,
    }
  }

  return {
    props: {
      user,
      title: `${topic.title} - HAKKA!`,
    },
  }
}
Example #20
Source File: [[...params]].tsx    From reddium with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async ({
  req,
  res,
  query
}) => {
  const cookies = new Cookies(req, res);
  const token = cookies.get("token") || "";
  const commentId =
    query.hasOwnProperty("params") && query.params.length > 1
      ? query.params[1]
      : "";
  const post = await getPostInfo({
    ...query,
    commentid: commentId,
    token: token
  });
  return {
    props: {
      ...post,
      params: {
        ...query,
        token: token
      },
      commentId: commentId
    }
  };
}
Example #21
Source File: [carId].tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = 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 #22
Source File: [username].tsx    From hakka with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<PageProps> = async (
  ctx,
) => {
  const { user } = await getServerSession(ctx.req)

  return {
    props: {
      user,
    },
  }
}
Example #23
Source File: cars.tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async () => {
  const carList = await api.getCarList();
  console.log('Car list build time:', { carList });
  return {
    props: {
      carList,
    },
  };
}
Example #24
Source File: settings.tsx    From hakka with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<PageProps> = async (
  ctx,
) => {
  const { user } = await getServerSession(ctx.req)

  if (!user) {
    return {
      redirect: {
        destination: '/login',
        statusCode: 302,
      },
    }
  }

  return {
    props: {
      user,
    },
  }
}
Example #25
Source File: index.tsx    From NextLevelWeek with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = async (ctx) => {
    // Recuperando os dados do cookie.
    const { level, currentExp, challengesCompleted } = ctx.req.cookies;

    return {
        props: {
            level: Number(level),
            currentExp: Number(currentExp),
            challengesCompleted: Number(challengesCompleted),
        },
    };
}
Example #26
Source File: [carId].tsx    From master-frontend-lemoncode with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps = 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 #27
Source File: account.tsx    From ultimate-saas-ts with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<Props> = async (
  context
) => {
  const session = await getSession(context);
  const subscription = await prisma.subscription.findFirst({
    where: {
      userId: (session?.user as any)?.userId,
      status: {
        in: ['active', 'trialing'],
      },
    },
    include: {
      price: {
        include: {
          product: true,
        },
      },
    },
  });

  return {
    redirect: !session && {
      destination: '/api/auth/signin',
      permanent: false,
    },
    props: {
      subscription,
    },
  };
}
Example #28
Source File: index.tsx    From nextjs-hasura-fullstack with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps<IndexPageProps> = async (
  ctx,
) => {
  const session = await getSession(ctx as any)

  return {
    props: {
      session,
    },
  }
}
Example #29
Source File: rss.xml.tsx    From next-cms-ghost with MIT License 6 votes vote down vote up
getServerSideProps: GetServerSideProps | undefined = process.env.IS_EXPORT
  ? undefined
  : async ({ res }) => {
      let settings
      let posts: GhostPostsOrPages | []

      try {
        settings = await getAllSettings()
        posts = await getAllPosts()
      } catch (error) {
        throw new Error('Index creation failed.')
      }

      let rssData = null
      if (settings.processEnv.rssFeed) {
        rssData = generateRSSFeed({ posts, settings })
      }

      if (res && rssData) {
        res.setHeader('Content-Type', 'text/xml')
        res.write(rssData)
        res.end()
      }

      return {
        props: {},
      }
    }