Skip to content

Commit

Permalink
feat: multisite compatible getSettings and API functions (#275)
Browse files Browse the repository at this point in the history
* multisite compatible getSettings and API functions

* only need requeste on api calls

* fully use getSettings to render our wildcard route

* basic WIP docs on multisite

* refactor meta/header to use THEME

* minimal config in constants
  • Loading branch information
ccorda authored Aug 10, 2023
1 parent 58911bf commit 5a4c3e1
Show file tree
Hide file tree
Showing 13 changed files with 279 additions and 91 deletions.
6 changes: 6 additions & 0 deletions docs/multisite.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Multisite

In version 1.4, we introduced the getSettings object, which allows you to configure the site's settings via a middleware function in addition to ENV variables. This allows you to configure the site's settings based on the current request, which is useful for multisite setups.

More to come on this approach in the future, but for now you can see more on the Vercel site on how they accomplish this:
https://vercel.com/guides/nextjs-multi-tenant-application#4.-configure-rewrites-for-multi-tenancy
6 changes: 3 additions & 3 deletions website/src/components/Header.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import cx from 'classnames';
import GlobalsContext from 'contexts/GlobalsContext';
import { META } from 'lib/constants';
import formatMenu from 'lib/formatMenu';
import Link from 'next/link';
import { useContext, useState } from 'react';
Expand All @@ -9,6 +8,7 @@ import styles from './Header.module.scss';

export default function Header() {
const globals = useContext(GlobalsContext);
const THEME = globals.THEME;
const [navOpen, setNavOpen] = useState(false);

function handleHamburgerClick() {
Expand Down Expand Up @@ -104,10 +104,10 @@ export default function Header() {
<div className="container">
<div className="row align-items-center justify-content-between">
<div className="col">
{META.siteName && (
{THEME.meta.siteName && (
<div className={styles.logo}>
<Link href="/" prefetch={false}>
{META.siteName}
{THEME.meta.siteName}
</Link>
</div>
)}
Expand Down
23 changes: 13 additions & 10 deletions website/src/components/Meta.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,38 @@
import GlobalsContext from 'contexts/GlobalsContext';
import { META, WORDPRESS_URL } from 'lib/constants';
import { trimTrailingSlash } from 'lib/utils';
import { NextSeo } from 'next-seo';
import Head from 'next/head';
import { useContext } from 'react';

export default function Meta({ title, description, image, seo }) {
const globals = useContext(GlobalsContext);
const THEME = globals.THEME;
const CONFIG = globals.CONFIG;

// make sure image is absolute
function imagePath(imageUrl) {
// if enabled rewrite WordPress image paths to local (origin often has noindex tags)
if (META.proxyWordPressImages && WORDPRESS_URL) {
let newUrl = imageUrl.replace(WORDPRESS_URL, '');
if (THEME.meta.proxyWordPressImages && CONFIG.wordpress_url) {
let newUrl = imageUrl.replace(CONFIG.wordpress_url, '');
imageUrl = newUrl;
}
// if root relative, make absolute so that twitter doesn't complain
if (
imageUrl.indexOf('http://') === -1 &&
imageUrl.indexOf('https://') === -1 &&
META.url &&
THEME.meta.url &&
imageUrl.startsWith('/')
) {
imageUrl = trimTrailingSlash(META.url) + imageUrl;
imageUrl = trimTrailingSlash(THEME.meta.url) + imageUrl;
}

return imageUrl;
}

// if passing in a title string, append default append if defined in META.
let generatedTitle = title ? `${title} ${META.titleAppend}` : '';
let generatedTitle = title
? `${title} ${THEME.meta.titleAppend}`
: '';

// populate SEO settings with either our SEO values if present, otherwise passed in specifics
let seoSettings = {
Expand Down Expand Up @@ -79,13 +82,13 @@ export default function Meta({ title, description, image, seo }) {
/>
<meta charSet="utf-8" key="meta_charset" />
{/* favicons */}
{META.icon32 && (
<link rel="icon" href={META.icon32} sizes="32x32" />
{THEME.meta.icon32 && (
<link rel="icon" href={THEME.meta.icon32} sizes="32x32" />
)}
{META.iconApple && (
{THEME.meta.iconApple && (
<link
rel="apple-touch-icon"
href={META.iconApple}
href={THEME.meta.iconApple}
sizes="180x180"
/>
)}
Expand Down
18 changes: 18 additions & 0 deletions website/src/components/layouts/LayoutDefault.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import Footer from 'components/Footer';
import Header from 'components/Header';
import Meta from 'components/Meta';
import PreviewModeBar from 'components/PreviewModeBar';
import GlobalsContext from 'contexts/GlobalsContext';
import { DefaultSeo } from 'next-seo';
import { useContext } from 'react';

export default function LayoutDefault({
children,
Expand All @@ -13,8 +16,23 @@ export default function LayoutDefault({
isRevision,
preview,
}) {
const globals = useContext(GlobalsContext);
const THEME = globals.THEME;

return (
<>
<DefaultSeo
defaultTitle={THEME?.meta?.siteName}
openGraph={{
type: 'website',
locale: 'en_US',
site_name: THEME?.meta?.siteName,
}}
twitter={{
handle: THEME?.meta?.twitterHandle,
cardType: 'summary_large_image',
}}
/>
<Meta
title={title}
description={description}
Expand Down
38 changes: 29 additions & 9 deletions website/src/lib/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,33 @@ export const WORDPRESS_API_URL =
(WORDPRESS_URL && WORDPRESS_URL + '/graphql') ||
'https://bubsnext.wpengine.com/graphql';

/** SEO Tags */
export const META = {
titleAppend: '| Patronage',
url: 'https://bubs.patronage.org',
twitterHandle: '@patronageorg',
siteName: 'Bubs by Patronage',
proxyWordPressImages: true,
icon32: '',
iconApple: '/apple-touch-icon.png',
// TODO: Should these be camelCase?/
export const CONFIG = {
site_domain: 'bubs.patronage.org',
wordpress_domain: WORDPRESS_DOMAIN,
wordpress_url: WORDPRESS_URL,
wordpress_api_url: WORDPRESS_API_URL,
graphcdn_purge_api_url: process.env.GRAPHCDN_PURGE_API_URL || '',
graphcdn_purge_api_token:
process.env.GRAPHCDN_PURGE_API_TOKEN || '',
};

// Theme defaults, these get merged with the project config
export const THEME = {
meta: {
icon32: '',
iconApple: '/apple-touch-icon.png',
titleAppend: '| Patronage',
url: 'https://bubs.patronage.org',
twitterHandle: '@patronageorg',
siteName: 'Bubs by Patronage',
proxyWordPressImages: true,
},
i18n: {
enabled: false,
},
integrations: {
googleAnalyticsID: '',
googleTagManagerID: '',
},
};
91 changes: 91 additions & 0 deletions website/src/lib/getSettings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import {
LAUNCH_PROJECT_CONFIGS,
THEME_BASE,
CONFIG,
THEME,
} from 'lib/constants';
import _merge from 'lodash/merge';

/**
* Returns site settings either from a multisite lookup, or from defined constants
* Hostname comes from the middleware.
*
* @param {string} host [hostname of site]
* @param {string} project [project key of site]
*
* @return {object} [PROJECT, CONFIG, THEME objects]
*/
export function getSettings({ req, host, project }) {
const multisite = process.env.MULTISITE || false;

if (multisite) {
const launchHost = host || req?.headers['x-launch-host'];
const launchProject = project || req?.headers['x-launch-project'];

return multisiteSettings({
host: launchHost,
project: launchProject,
});
}

return singleSiteSettings();
}

function singleSiteSettings() {
return {
PROJECT: null,
CONFIG: CONFIG,
THEME: THEME,
};
}

function multisiteSettings({ host, project }) {
// eslint-disable-next-line no-console
// console.log(`getSettings: host: ${host}, project: ${project}`);
if (!project && !host) {
throw new Error('No host or project provided');
}

// have host, lookup project
if (host && !project) {
// console.log(`looking up project from host: ${host}`);
// lookup project from hostname
const findKey = (obj, predicate = (o) => o) =>
Object.keys(obj).find((key) => predicate(obj[key], key, obj));

project = findKey(LAUNCH_PROJECT_CONFIGS, function (o) {
return o.site_domain == host;
});

if (!project) {
// if no match, use the ENV defined project
// console.log('no project still after host lookup, checking ENV');
project = process.env.NEXT_PUBLIC_LAUNCH_HOST;
}
}

if (project && !host) {
// console.log('no host provided, must have project only');
// todo, set host do we need to repeat logic from middleware?
// should be DRY
}

if (project && !LAUNCH_PROJECT_CONFIGS[project]) {
throw new Error(
`Project '${project}' does not exist in LAUNCH_PROJECT_CONFIGS`,
);
}

// https://stackoverflow.com/questions/28044373/use-lo-dash-merge-without-modifying-underlying-object
const merged = _merge(
{},
THEME_BASE,
LAUNCH_PROJECT_CONFIGS[project].theme,
);

return {
PROJECT: project,
CONFIG: LAUNCH_PROJECT_CONFIGS[project].config,
THEME: merged,
};
}
Loading

1 comment on commit 5a4c3e1

@vercel
Copy link

@vercel vercel bot commented on 5a4c3e1 Aug 10, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.