Skip to content

Commit

Permalink
feat: app router multisite
Browse files Browse the repository at this point in the history
  • Loading branch information
nicholasio committed Jul 15, 2024
1 parent 4f7a665 commit 5cccea4
Show file tree
Hide file tree
Showing 29 changed files with 548 additions and 14 deletions.
7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@
"test:watch": "turbo run test:watch",
"lint": "turbo run lint",
"wp-env": "npm run wp-env:start -w=wp/headless-wp",
"dev": "turbo run dev --parallel --filter=!./projects/wp-multisite-nextjs --filter=!./projects/wp-multisite-i18n-nextjs",
"dev:app": "turbo run dev --parallel --filter=!./projects/wp-multisite-nextjs --filter=!./projects/wp-multisite-i18n-nextjs --filter=!./projects/wp-nextjs",
"dev:multisite": "turbo run dev --parallel --filter=!./projects/wp-nextjs",
"dev": "turbo run dev --parallel --filter=./projects/wp-nextjs --filter=./packages/core --filter=./packages/next",
"dev:app": "turbo run dev --parallel --filter=./projects/wp-nextjs-app --filter=./packages/core --filter=./packages/next",
"dev:app:multisite": "turbo run dev --parallel --filter=./projects/wp-multisite-nextjs-app --filter=./packages/core --filter=./packages/next",
"dev:multisite": "turbo run dev --parallel --filter=./projects/wp-multisite-nextjs --filter=./packages/core --filter=./packages/next",
"prepare": "husky install",
"typedoc": "typedoc",
"typedoc:watch": "typedoc --watch",
Expand Down
16 changes: 10 additions & 6 deletions packages/next/src/middlewares/appMidleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export async function AppMiddleware(
options: AppMidlewareOptions = { appRouter: false },
) {
let response = NextResponse.next();

const currentUrl = req.nextUrl.pathname;
if (isStaticAssetRequest(req) || isInternalRequest(req)) {
return response;
}
Expand Down Expand Up @@ -52,16 +52,20 @@ export async function AppMiddleware(
}

if (isMultisiteRequest) {
const hostname = req.headers.get('host') || '';

const url = req.nextUrl;
url.pathname = `/_sites/${hostname}${url.pathname}`;

response = NextResponse.rewrite(url);
response = NextResponse.rewrite(
new URL(
options.appRouter
? `/${hostname}${url.pathname}`
: `/_sites/${hostname}${url.pathname}`,
url,
),
);
response.headers.set('x-headstartwp-site', hostname);
}

response.headers.set('x-headstartwp-current-url', req.nextUrl.pathname);
response.headers.set('x-headstartwp-current-url', currentUrl);

return response;
}
4 changes: 3 additions & 1 deletion packages/next/src/rsc/data/queries/prepareQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ export function prepareQuery<P>(
const { routeParams, ...rest } = query;

const path = routeParams?.path ?? '';
const siteConfig = routeParams?.site ? getSiteByHost(routeParams?.site) : null;
const siteConfig = routeParams?.site
? getSiteByHost(decodeURIComponent(routeParams?.site))
: null;

if (routeParams?.site && !siteConfig) {
throw new FrameworkError(
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/rsc/data/queries/queryAppSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ import {
} from '@headstartwp/core';
import { handleFetchError } from '../handleFetchError';
import { prepareQuery } from './prepareQuery';
import { NextQueryProps } from './types';

export async function queryAppSettings<
T extends AppEntity = AppEntity,
P extends EndpointParams = EndpointParams,
>(q: AppQueryProps<P> = {}, _config: HeadlessConfig | undefined = undefined) {
>(q: AppQueryProps<P> & NextQueryProps<P> = {}, _config: HeadlessConfig | undefined = undefined) {
const { config, ...query } = prepareQuery<P>(q, _config);

try {
Expand Down
5 changes: 5 additions & 0 deletions packages/next/src/rsc/types.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
export type HeadstartWPRoute<Params extends { [k: string]: unknown } = {}> = {
params: { path: string[]; site?: string };
} & Params;

export type HeadstartWPLayout<Params extends { [k: string]: unknown } = {}> = {
params: { site?: string };
children: React.ReactNode;
} & Params;
2 changes: 2 additions & 0 deletions projects/wp-multisite-nextjs-app/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
NEXT_PUBLIC_HEADLESS_WP_URL=https://js1.10up.com
NEXT_PUBLIC_HOST_URL=https://js1.10up.com
14 changes: 14 additions & 0 deletions projects/wp-multisite-nextjs-app/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
module.exports = {
extends: ['@10up/eslint-config/react'],
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint'],
settings: {
jsdoc: {
mode: 'typescript',
},
},
rules: {
'react/require-default-props': ['error', { functions: 'defaultArguments' }],
'jsdoc/require-returns-type': 'off',
},
};
36 changes: 36 additions & 0 deletions projects/wp-multisite-nextjs-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# testing
/coverage

# next.js
/.next/
/out/

# production
/build

# misc
.DS_Store
*.pem

# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# local env files
.env*.local

# vercel
.vercel

# typescript
*.tsbuildinfo
next-env.d.ts
36 changes: 36 additions & 0 deletions projects/wp-multisite-nextjs-app/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org/) project bootstrapped with [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app).

## Getting Started

First, run the development server:

```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```

Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.

You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.

This project uses [`next/font`](https://nextjs.org/docs/basic-features/font-optimization) to automatically optimize and load Inter, a custom Google Font.

## Learn More

To learn more about Next.js, take a look at the following resources:

- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.

You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js/) - your feedback and contributions are welcome!

## Deploy on Vercel

The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.

Check out our [Next.js deployment documentation](https://nextjs.org/docs/deployment) for more details.
23 changes: 23 additions & 0 deletions projects/wp-multisite-nextjs-app/headstartwp.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Headless Config
*
* @type {import('@headstartwp/core').HeadlessConfig}
*/
module.exports = {
useWordPressPlugin: true,

preview: {
usePostLinkForRedirect: true,
},

sites: [
{
sourceUrl: process.env.NEXT_PUBLIC_HEADLESS_WP_URL,
hostUrl: 'http://site1.localhost:3000',
},
{
sourceUrl: 'https://js1.10up.com/',
hostUrl: 'http://js1.localhost:3000',
},
],
};
16 changes: 16 additions & 0 deletions projects/wp-multisite-nextjs-app/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const { withHeadstartWPConfig } = require('@headstartwp/next/config');

/** @type {import('next').NextConfig} */
const nextConfig = {
webpack: (config) => {
// TODO: figure out why this is needed
config.resolve = {
...config.resolve,
conditionNames: ['import'],
};

return config;
},
};

module.exports = withHeadstartWPConfig(nextConfig);
27 changes: 27 additions & 0 deletions projects/wp-multisite-nextjs-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"name": "@10up/wp-multisite-nextjs-app",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"react": "^18",
"react-dom": "^18",
"next": "14.2.3",
"@headstartwp/core": "^1.4.3",
"@headstartwp/next": "^1.4.2"
},
"devDependencies": {
"@10up/eslint-config": "^4.0.0",
"typescript": "^5",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^8",
"eslint-config-next": "14.2.3"
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,26 @@
import { BlocksRenderer, HtmlDecoder } from '@headstartwp/core/react';
import { HeadstartWPRoute, queryPost } from '@headstartwp/next/app';

const Single = async ({ params }: HeadstartWPRoute) => {
const { data } = await queryPost({
routeParams: params,
params: {
matchCurrentPath: false,
postType: ['post', 'page'],
},
options: {
headers: {
cache: 'no-store',
cache: 'force-cache',
},
},
});

return (
<article>
<h1>{data.post.title.rendered}</h1>
<h1>
<HtmlDecoder html={data.post.title.rendered ?? ''} />
</h1>

<BlocksRenderer html={data.post.content.rendered ?? ''} />
</article>
);
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { HeadstartWPRoute, queryAuthorArchive } from '@headstartwp/next/app';
import Link from 'next/link';

const AuthorArchive = async ({ params }: HeadstartWPRoute) => {
const { data } = await queryAuthorArchive({
routeParams: params,
});

return (
<article>
<h1>{data.queriedObject.author?.name}</h1>

<ul>
{data.posts.map((post) => (
<li key={post.id}>
<Link href={post.link}>{post.title.rendered}</Link>
</li>
))}
</ul>
</article>
);
};

export default AuthorArchive;
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import { PostEntity, QueriedObject } from '@headstartwp/core';
import { HeadstartWPRoute, queryPostOrPosts } from '@headstartwp/next/app';
import Link from 'next/link';
import { notFound } from 'next/navigation';

type ArchiveProps = {
posts: PostEntity[];
queriedObject: QueriedObject;
};

const Archive = ({ posts, queriedObject }: ArchiveProps) => {
return (
<main>
<h1>{queriedObject.term?.name}</h1>

<ul>
{posts.map((post) => (
<li key={post.id}>
<Link href={post.link}>{post.title.rendered}</Link>
</li>
))}
</ul>
</main>
);
};

const BlogPage = async ({ params }: HeadstartWPRoute) => {
const { isArchive, isSingle, data } = await queryPostOrPosts({
routeParams: params,
params: {
single: {
postType: 'post',
},
archive: {
postType: 'post',
/**
* Specifying the _fields param reduces the amount of data queried and returned by the API.
*/
_fields: ['id', 'title', 'link'],
},
priority: 'single',
routeMatchStrategy: 'single',
},
});

if (isArchive && typeof data.posts !== 'undefined') {
return <Archive posts={data.posts} queriedObject={data.queriedObject} />;
}

if (isSingle && typeof data.post !== 'undefined') {
return (
<article>
<h1>{data.post.title.rendered}</h1>
</article>
);
}

return notFound();
};

export default BlogPage;
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { HeadstartWPRoute, queryPosts } from '@headstartwp/next/app';
import Link from 'next/link';

const CategoryArchive = async ({ params }: HeadstartWPRoute) => {
const { data } = await queryPosts({
routeParams: params,
params: {
taxonomy: 'category',
},
});

return (
<article>
<h1>{data.queriedObject.term?.name}</h1>

<ul>
{data.posts.map((post) => (
<li key={post.id}>
<Link href={post.link}>{post.title.rendered}</Link>
</li>
))}
</ul>
</article>
);
};

export default CategoryArchive;
Binary file not shown.
Loading

0 comments on commit 5cccea4

Please sign in to comment.