Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
♻️ Refactor code for generating absolute url (#904)
Luke Vella703d551aac76
diff --git a/apps/landing/src/pages/_app.tsx b/apps/landing/src/pages/_app.tsxindex 6eace7278..39929591d 100644--- a/apps/landing/src/pages/_app.tsx+++ b/apps/landing/src/pages/_app.tsx@@ -2,7 +2,6 @@ import "tailwindcss/tailwind.css";import "../style.css";import { trpc, UserSession } from "@rallly/backend/next/trpc/client";-import { absoluteUrl } from "@rallly/utils";import { inject } from "@vercel/analytics";import dayjs from "dayjs";import localizedFormat from "dayjs/plugin/localizedFormat";@@ -16,6 +15,8 @@ import { appWithTranslation } from "next-i18next";import { DefaultSeo, SoftwareAppJsonLd } from "next-seo";import React from "react";+import { absoluteUrl } from "@/utils/absolute-url";+import * as nextI18nNextConfig from "../../next-i18next.config.js";import { NextPageWithLayout } from "../types";diff --git a/apps/landing/src/pages/blog/[slug].tsx b/apps/landing/src/pages/blog/[slug].tsxindex 91c7a9981..fc6db6656 100644--- a/apps/landing/src/pages/blog/[slug].tsx+++ b/apps/landing/src/pages/blog/[slug].tsx@@ -1,5 +1,4 @@import { ArrowLeftIcon } from "@rallly/icons";-import { absoluteUrl } from "@rallly/utils";import { GetStaticPropsContext } from "next";import ErrorPage from "next/error";import Head from "next/head";@@ -14,6 +13,7 @@ import { getBlogLayout } from "@/components/layouts/blog-layout";import { getAllPosts, getPostBySlug } from "@/lib/api";import markdownToHtml from "@/lib/markdownToHtml";import { NextPageWithLayout, Post } from "@/types";+import { absoluteUrl } from "@/utils/absolute-url";import { getStaticTranslations } from "@/utils/page-translations";type Props = {diff --git a/packages/utils/src/absolute-url.ts b/apps/landing/src/utils/absolute-url.tssimilarity index 82%rename from packages/utils/src/absolute-url.tsrename to apps/landing/src/utils/absolute-url.tsindex 6dd353603..c0b8b0153 100644--- a/packages/utils/src/absolute-url.ts+++ b/apps/landing/src/utils/absolute-url.ts@@ -28,8 +28,3 @@ export function absoluteUrl(subpath = "", query?: Record<string, string>) {return joinPath(baseUrl, subpath) + queryString;}--export function shortUrl(subpath = "") {- const baseUrl = process.env.NEXT_PUBLIC_SHORT_BASE_URL ?? absoluteUrl();- return joinPath(baseUrl, subpath);-}diff --git a/apps/web/declarations/environment.d.ts b/apps/web/declarations/environment.d.tsindex 02a71d140..a91ab98d9 100644--- a/apps/web/declarations/environment.d.ts+++ b/apps/web/declarations/environment.d.ts@@ -9,10 +9,6 @@ declare global {* "development" or "production"*/NODE_ENV: "development" | "production";- /**- * Set to "true" to take users straight to app instead of landing page- */- DISABLE_LANDING_PAGE?: string;/*** Must be 32 characters long*/@@ -84,10 +80,6 @@ declare global {* The app version just for reference*/NEXT_PUBLIC_APP_VERSION?: string;- /**- * "true" to enable finalization of polls- */- NEXT_PUBLIC_ENABLE_FINALIZATION?: string;}}}diff --git a/apps/web/src/components/invite-dialog.tsx b/apps/web/src/components/invite-dialog.tsxindex e3eb9d3ed..cb98c2bd2 100644--- a/apps/web/src/components/invite-dialog.tsx+++ b/apps/web/src/components/invite-dialog.tsx@@ -8,7 +8,6 @@ import {DialogTitle,DialogTrigger,} from "@rallly/ui/dialog";-import { shortUrl } from "@rallly/utils";import Link from "next/link";import React from "react";import { useCopyToClipboard } from "react-use";@@ -16,6 +15,7 @@ import { useCopyToClipboard } from "react-use";import { useParticipants } from "@/components/participants-provider";import { Trans } from "@/components/trans";import { usePoll } from "@/contexts/poll";+import { shortUrl } from "@/utils/absolute-url";import { isSelfHosted } from "@/utils/constants";export const InviteDialog = () => {diff --git a/apps/web/src/pages/api/stripe/checkout.ts b/apps/web/src/pages/api/stripe/checkout.tsindex 9e30c38d9..3369bf71d 100644--- a/apps/web/src/pages/api/stripe/checkout.ts+++ b/apps/web/src/pages/api/stripe/checkout.ts@@ -1,10 +1,11 @@import { getSession } from "@rallly/backend/next/session";import { stripe } from "@rallly/backend/stripe";import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils";import { NextApiRequest, NextApiResponse } from "next";import { z } from "zod";+import { absoluteUrl } from "@/utils/absolute-url";+export const config = {edge: true,};diff --git a/apps/web/src/pages/api/stripe/portal.ts b/apps/web/src/pages/api/stripe/portal.tsindex a53db38ff..c440402c0 100644--- a/apps/web/src/pages/api/stripe/portal.ts+++ b/apps/web/src/pages/api/stripe/portal.ts@@ -1,10 +1,11 @@import { getSession } from "@rallly/backend/next/session";import { stripe } from "@rallly/backend/stripe";import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils";import { NextApiRequest, NextApiResponse } from "next";import { z } from "zod";+import { absoluteUrl } from "@/utils/absolute-url";+const inputSchema = z.object({session_id: z.string().optional(),return_path: z.string().optional(),diff --git a/apps/web/src/pages/api/trpc/[trpc].ts b/apps/web/src/pages/api/trpc/[trpc].tsindex 1d59bae6d..186df892d 100644--- a/apps/web/src/pages/api/trpc/[trpc].ts+++ b/apps/web/src/pages/api/trpc/[trpc].ts@@ -1,6 +1,7 @@import { trpcNextApiHandler } from "@rallly/backend/next/trpc/server";import { NextApiRequest, NextApiResponse } from "next";+import { absoluteUrl, shortUrl } from "@/utils/absolute-url";import { getServerSession, isEmailBlocked } from "@/utils/auth";import { isSelfHosted } from "@/utils/constants";import { emailClient } from "@/utils/emails";@@ -31,5 +32,7 @@ export default async function handler(emailClient,isSelfHosted,isEmailBlocked,+ absoluteUrl,+ shortUrl,})(req, res);}diff --git a/apps/web/src/pages/invite/[urlId].tsx b/apps/web/src/pages/invite/[urlId].tsxindex 444bdbe1f..12cb2c87a 100644--- a/apps/web/src/pages/invite/[urlId].tsx+++ b/apps/web/src/pages/invite/[urlId].tsx@@ -2,7 +2,6 @@ import { trpc } from "@rallly/backend";import { prisma } from "@rallly/database";import { ArrowUpLeftIcon } from "@rallly/icons";import { Button } from "@rallly/ui/button";-import { absoluteUrl } from "@rallly/utils";import { GetStaticProps } from "next";import Head from "next/head";import Link from "next/link";@@ -19,6 +18,7 @@ import { UserProvider, useUser } from "@/components/user-provider";import { VisibilityProvider } from "@/components/visibility";import { PermissionsContext } from "@/contexts/permissions";import { usePoll } from "@/contexts/poll";+import { absoluteUrl } from "@/utils/absolute-url";import { ConnectedDayjsProvider } from "@/utils/dayjs";import { getStaticTranslations } from "@/utils/with-page-translations";diff --git a/apps/web/src/utils/absolute-url.ts b/apps/web/src/utils/absolute-url.tsindex fba32a0a5..6dd353603 100644--- a/apps/web/src/utils/absolute-url.ts+++ b/apps/web/src/utils/absolute-url.ts@@ -6,10 +6,30 @@ const getVercelUrl = () => {: null;};-export function absoluteUrl(path = "") {+function joinPath(baseUrl: string, subpath = "") {+ if (subpath) {+ const url = new URL(subpath, baseUrl);+ return url.href;+ }++ return baseUrl;+}++export function absoluteUrl(subpath = "", query?: Record<string, string>) {+ const queryString = query+ ? `?${Object.entries(query)+ .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)+ .join("&")}`+ : "";const baseUrl =process.env.NEXT_PUBLIC_BASE_URL ??getVercelUrl() ??`http://localhost:${port}`;- return `${baseUrl}${path}`;++ return joinPath(baseUrl, subpath) + queryString;+}++export function shortUrl(subpath = "") {+ const baseUrl = process.env.NEXT_PUBLIC_SHORT_BASE_URL ?? absoluteUrl();+ return joinPath(baseUrl, subpath);}diff --git a/apps/web/src/utils/emails.ts b/apps/web/src/utils/emails.tsindex 2cbbd8e37..504043f7a 100644--- a/apps/web/src/utils/emails.ts+++ b/apps/web/src/utils/emails.ts@@ -1,5 +1,7 @@import { EmailClient, SupportedEmailProviders } from "@rallly/emails";+import { absoluteUrl } from "@/utils/absolute-url";+const env = process.env["NODE" + "_ENV"];export const emailClient = new EmailClient({@@ -16,4 +18,8 @@ export const emailClient = new EmailClient({(process.env.SUPPORT_EMAIL as string),},},+ context: {+ logoUrl: absoluteUrl("/logo.png"),+ baseUrl: absoluteUrl(""),+ },});diff --git a/packages/backend/next/trpc/server.ts b/packages/backend/next/trpc/server.tsindex 5a26cdb0c..ad5c52035 100644--- a/packages/backend/next/trpc/server.ts+++ b/packages/backend/next/trpc/server.ts@@ -8,6 +8,13 @@ export interface TRPCContext {emailClient: EmailClient;isSelfHosted: boolean;isEmailBlocked?: (email: string) => boolean;+ /**+ * Takes a relative path and returns an absolute URL to the app+ * @param path+ * @returns absolute URL+ */+ absoluteUrl: (path?: string) => string;+ shortUrl: (path?: string) => string;}export const trpcNextApiHandler = (context: TRPCContext) => {diff --git a/packages/backend/trpc/routers/polls.ts b/packages/backend/trpc/routers/polls.tsindex 9ae6646ac..885fe6946 100644--- a/packages/backend/trpc/routers/polls.ts+++ b/packages/backend/trpc/routers/polls.ts@@ -1,5 +1,4 @@import { prisma } from "@rallly/database";-import { absoluteUrl, shortUrl } from "@rallly/utils";import { TRPCError } from "@trpc/server";import dayjs from "dayjs";import timezone from "dayjs/plugin/timezone";@@ -121,9 +120,9 @@ export const polls = router({},});- const pollLink = absoluteUrl(`/poll/${pollId}`);+ const pollLink = ctx.absoluteUrl(`/poll/${pollId}`);- const participantLink = shortUrl(`/invite/${pollId}`);+ const participantLink = ctx.shortUrl(`/invite/${pollId}`);if (ctx.user.isGuest === false) {const user = await prisma.user.findUnique({@@ -658,7 +657,7 @@ export const polls = router({to: poll.user.email,props: {name: poll.user.name,- pollUrl: absoluteUrl(`/poll/${poll.id}`),+ pollUrl: ctx.absoluteUrl(`/poll/${poll.id}`),location: poll.location,title: poll.title,attendees: poll.participants@@ -682,7 +681,7 @@ export const polls = router({to: p.email,props: {name: p.name,- pollUrl: absoluteUrl(`/poll/${poll.id}`),+ pollUrl: ctx.absoluteUrl(`/poll/${poll.id}`),location: poll.location,title: poll.title,hostName: poll.user?.name ?? "",diff --git a/packages/backend/trpc/routers/polls/comments.ts b/packages/backend/trpc/routers/polls/comments.tsindex c8daa3516..77d76d5bc 100644--- a/packages/backend/trpc/routers/polls/comments.ts+++ b/packages/backend/trpc/routers/polls/comments.ts@@ -1,5 +1,4 @@import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils";import { z } from "zod";import { createToken } from "../../../session";@@ -87,8 +86,8 @@ export const comments = router({props: {name: watcher.user.name,authorName,- pollUrl: absoluteUrl(`/poll/${poll.id}`),- disableNotificationsUrl: absoluteUrl(+ pollUrl: ctx.absoluteUrl(`/poll/${poll.id}`),+ disableNotificationsUrl: ctx.absoluteUrl(`/auth/disable-notifications?token=${token}`,),title: poll.title,diff --git a/packages/backend/trpc/routers/polls/participants.ts b/packages/backend/trpc/routers/polls/participants.tsindex 08b053b6e..555987c69 100644--- a/packages/backend/trpc/routers/polls/participants.ts+++ b/packages/backend/trpc/routers/polls/participants.ts@@ -1,5 +1,4 @@import { prisma } from "@rallly/database";-import { absoluteUrl } from "@rallly/utils";import { TRPCError } from "@trpc/server";import { z } from "zod";@@ -112,7 +111,7 @@ export const participants = router({props: {name,title: poll.title,- editSubmissionUrl: absoluteUrl(+ editSubmissionUrl: ctx.absoluteUrl(`/invite/${poll.id}?token=${token}`,),},@@ -149,8 +148,8 @@ export const participants = router({props: {name: watcher.user.name,participantName: participant.name,- pollUrl: absoluteUrl(`/poll/${poll.id}`),- disableNotificationsUrl: absoluteUrl(+ pollUrl: ctx.absoluteUrl(`/poll/${poll.id}`),+ disableNotificationsUrl: ctx.absoluteUrl(`/auth/disable-notifications?token=${token}`,),title: poll.title,diff --git a/packages/emails/src/send-email.tsx b/packages/emails/src/send-email.tsxindex 8e6472fcb..077aac91d 100644--- a/packages/emails/src/send-email.tsx+++ b/packages/emails/src/send-email.tsx@@ -7,6 +7,7 @@ import previewEmail from "preview-email";import React from "react";import * as templates from "./templates";+import { EmailContext } from "./templates/components/email-context";type Templates = typeof templates;@@ -15,7 +16,6 @@ type TemplateName = keyof typeof templates;type TemplateProps<T extends TemplateName> = React.ComponentProps<TemplateComponent<T>>;-type TemplateComponent<T extends TemplateName> = Templates[T];type SendEmailOptions<T extends TemplateName> = {@@ -59,6 +59,10 @@ type EmailClientConfig = {address: string;};};+ /**+ * Context to pass to each email+ */+ context: EmailContext;};export class EmailClient {@@ -79,8 +83,14 @@ export class EmailClient {}const Template = templates[templateName] as TemplateComponent<T>;- // eslint-disable-next-line @typescript-eslint/no-explicit-any- const html = render(<Template {...(options.props as any)} />);+ const html = render(+ <EmailContext.Provider value={this.config.context}>+ <Template+ // eslint-disable-next-line @typescript-eslint/no-explicit-any+ {...(options.props as any)}+ />+ </EmailContext.Provider>,+ );try {await this.sendEmail({diff --git a/packages/emails/src/templates/components/email-context.tsx b/packages/emails/src/templates/components/email-context.tsxnew file mode 100644index 000000000..8e65cc308--- /dev/null+++ b/packages/emails/src/templates/components/email-context.tsx@@ -0,0 +1,19 @@+import React from "react";++export type EmailContext = {+ logoUrl: string;+ baseUrl: string;+};++export const EmailContext = React.createContext<EmailContext>({+ logoUrl: "",+ baseUrl: "",+});++export const useEmailContext = () => {+ const context = React.useContext(EmailContext);+ return {+ ...context,+ domain: context.baseUrl.replace(/(^\w+:|^)\/\//, ""),+ };+};diff --git a/packages/emails/src/templates/components/email-layout.tsx b/packages/emails/src/templates/components/email-layout.tsxindex 620dfbb48..feccb968a 100644--- a/packages/emails/src/templates/components/email-layout.tsx+++ b/packages/emails/src/templates/components/email-layout.tsx@@ -1,4 +1,3 @@-import { absoluteUrl } from "@rallly/utils";import {Body,Container,@@ -9,6 +8,7 @@ import {Preview,} from "@react-email/components";+import { useEmailContext } from "./email-context";import { fontFamily, Section, Text } from "./styled-components";export interface EmailLayoutProps {@@ -43,13 +43,14 @@ export const EmailLayout = ({children,footNote,}: React.PropsWithChildren<EmailLayoutProps>) => {+ const { logoUrl, baseUrl } = useEmailContext();return (<Html><Head /><Preview>{preview}</Preview><Body style={{ backgroundColor: "#F3F4F6", padding: "16px" }}><Container style={containerStyles}>- <Img src={absoluteUrl("/logo.png")} alt="Rallly" width={128} />+ <Img src={logoUrl} alt="Rallly" width={128} /><Section style={sectionStyles}><Text>Hi {recipientName},</Text>{children}@@ -68,7 +69,7 @@ export const EmailLayout = ({) : null}</Section><Section style={{ ...sectionStyles, fontSize: 14, marginBottom: 0 }}>- <Link style={linkStyles} href={absoluteUrl()}>+ <Link style={linkStyles} href={baseUrl}>Home</Link><span> • </span>diff --git a/packages/emails/src/templates/components/notification-email.tsx b/packages/emails/src/templates/components/notification-email.tsxindex d5f7e4e46..83399f06c 100644--- a/packages/emails/src/templates/components/notification-email.tsx+++ b/packages/emails/src/templates/components/notification-email.tsx@@ -1,6 +1,6 @@+import { useEmailContext } from "./email-context";import { EmailLayout } from "./email-layout";import { Button, Link, Text } from "./styled-components";-import { getDomain } from "./utils";export interface NotificationBaseProps {name: string;@@ -20,6 +20,7 @@ export const NotificationEmail = ({preview,children,}: React.PropsWithChildren<NotificationEmailProps>) => {+ const { domain } = useEmailContext();return (<EmailLayoutrecipientName={name}@@ -36,7 +37,7 @@ export const NotificationEmail = ({>{children}<Text>- <Button href={pollUrl}>View on {getDomain()}</Button>+ <Button href={pollUrl}>View on {domain}</Button></Text></EmailLayout>);diff --git a/packages/emails/src/templates/components/styled-components.tsx b/packages/emails/src/templates/components/styled-components.tsxindex f6b9d94ba..4e7da529f 100644--- a/packages/emails/src/templates/components/styled-components.tsx+++ b/packages/emails/src/templates/components/styled-components.tsx@@ -1,4 +1,3 @@-import { absoluteUrl } from "@rallly/utils";import {Button as UnstyledButton,ButtonProps,@@ -11,7 +10,7 @@ import {TextProps,} from "@react-email/components";-import { getDomain } from "./utils";+import { useEmailContext } from "./email-context";export const borderColor = "#E2E8F0";export const Text = (@@ -34,7 +33,8 @@ export const Text = (};export const Domain = () => {- return <Link href={absoluteUrl()}>{getDomain()}</Link>;+ const { baseUrl, domain } = useEmailContext();+ return <Link href={baseUrl}>{domain}</Link>;};export const Button = (props: ButtonProps) => {diff --git a/packages/emails/src/templates/components/utils.ts b/packages/emails/src/templates/components/utils.tsdeleted file mode 100644index 0ceb1bbfd..000000000--- a/packages/emails/src/templates/components/utils.ts+++ /dev/null@@ -1,7 +0,0 @@-import { absoluteUrl } from "@rallly/utils";--export const removeProtocalFromUrl = (url: string) => {- return url.replace(/(^\w+:|^)\/\//, "");-};--export const getDomain = () => removeProtocalFromUrl(absoluteUrl());diff --git a/packages/emails/src/templates/login.tsx b/packages/emails/src/templates/login.tsxindex 55b983f7c..7fdfa8041 100644--- a/packages/emails/src/templates/login.tsx+++ b/packages/emails/src/templates/login.tsx@@ -1,3 +1,4 @@+import { useEmailContext } from "./components/email-context";import { EmailLayout } from "./components/email-layout";import {Button,@@ -7,7 +8,6 @@ import {Text,trackingWide,} from "./components/styled-components";-import { getDomain } from "./components/utils";interface LoginEmailProps {name: string;@@ -20,6 +20,7 @@ export const LoginEmail = ({code = "123456",magicLink = "https://rallly.co",}: LoginEmailProps) => {+ const { domain } = useEmailContext();return (<EmailLayoutfootNote={@@ -39,7 +40,7 @@ export const LoginEmail = ({<Heading>Option 1: Magic Link</Heading><Text>Click this magic link to log in on this device.</Text><Button href={magicLink} id="magicLink">- Log in to {getDomain()}+ Log in to {domain}</Button><Text light={true}>This link will expire in 15 minutes.</Text></Card>diff --git a/packages/emails/src/templates/new-participant-confirmation.tsx b/packages/emails/src/templates/new-participant-confirmation.tsxindex ea76d0a96..3d4a2d199 100644--- a/packages/emails/src/templates/new-participant-confirmation.tsx+++ b/packages/emails/src/templates/new-participant-confirmation.tsx@@ -1,6 +1,6 @@+import { useEmailContext } from "./components/email-context";import { EmailLayout } from "./components/email-layout";import { Button, Domain, Section, Text } from "./components/styled-components";-import { getDomain } from "./components/utils";interface NewParticipantConfirmationEmailProps {name: string;@@ -12,6 +12,7 @@ export const NewParticipantConfirmationEmail = ({name = "John",editSubmissionUrl = "https://rallly.co",}: NewParticipantConfirmationEmailProps) => {+ const { domain } = useEmailContext();return (<EmailLayoutfootNote={@@ -32,7 +33,7 @@ export const NewParticipantConfirmationEmail = ({</Text><Section><Button id="editSubmissionUrl" href={editSubmissionUrl}>- Review response on {getDomain()}+ Review response on {domain}</Button></Section></EmailLayout>diff --git a/packages/emails/src/templates/new-poll.tsx b/packages/emails/src/templates/new-poll.tsxindex a9d2b9a54..6f8bbfed7 100644--- a/packages/emails/src/templates/new-poll.tsx+++ b/packages/emails/src/templates/new-poll.tsx@@ -1,8 +1,6 @@-import { absoluteUrl } from "@rallly/utils";-+import { useEmailContext } from "./components/email-context";import { EmailLayout } from "./components/email-layout";import { Button, Card, Link, Text } from "./components/styled-components";-import { getDomain } from "./components/utils";export interface NewPollEmailProps {title: string;@@ -40,13 +38,14 @@ export const NewPollEmail = ({adminLink = "https://rallly.co/admin/abcdefg123",participantLink = "https://rallly.co/invite/wxyz9876",}: NewPollEmailProps) => {+ const { baseUrl, domain } = useEmailContext();return (<EmailLayoutfootNote={<>You are receiving this email because a new poll was created with this- email address on <Link href={absoluteUrl()}>{getDomain()}</Link>. If- this wasn't you, please ignore this email.+ email address on <Link href={baseUrl}>{domain}</Link>. If this+ wasn't you, please ignore this email.</>}recipientName={name}diff --git a/packages/utils/index.ts b/packages/utils/index.tsindex e7fffef94..eb634b9ac 100644--- a/packages/utils/index.ts+++ b/packages/utils/index.ts@@ -1,2 +1 @@-export * from "./src/absolute-url";export * from "./src/prevent-widows";