Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
5551cc2
Correct typo error
2chanhaeng Aug 2, 2025
58c2307
Fix type error
2chanhaeng Aug 2, 2025
acd9c72
Merge remote-tracking branch 'upstream/main'
2chanhaeng Aug 2, 2025
ee3839a
Merge remote-tracking branch 'upstream/main'
2chanhaeng Aug 3, 2025
3ce0065
Merge remote-tracking branch 'upstream/main'
2chanhaeng Aug 6, 2025
1c30bca
Merge remote-tracking branch 'upstream/main'
2chanhaeng Aug 6, 2025
5f368f5
Define utils to integrate with Next.js
2chanhaeng Aug 6, 2025
fb06e08
Add tsdown.config.ts to @fedify/nextjs
2chanhaeng Aug 6, 2025
36dd055
Add Next.js to `cli init`
2chanhaeng Aug 6, 2025
bce021e
Ignore `.pnpm-store/`
2chanhaeng Aug 6, 2025
4cfe968
Init @fedify/nextjs
2chanhaeng Aug 6, 2025
0936009
Added changes to `CHANGES.md` related with #313
2chanhaeng Aug 6, 2025
01aba0e
Add docs about `@fedify/nextjs`
2chanhaeng Aug 6, 2025
9e43d7c
Fix typo errors
2chanhaeng Aug 7, 2025
71880e5
Fix `next` package to `"catalog:"`
2chanhaeng Aug 8, 2025
1ec76db
Rename `@fedify/nextjs` to `@fedify/next`
2chanhaeng Aug 8, 2025
0cf46e6
Format docs
2chanhaeng Aug 8, 2025
da08eb5
Remove param types in TSDoc
2chanhaeng Aug 8, 2025
61647bb
Remove `x-forwarded-fetch`
2chanhaeng Aug 8, 2025
4f17015
Add docs about `@fedify/next`
2chanhaeng Aug 8, 2025
a0ed306
Ignore examples in doc when test doc
2chanhaeng Aug 8, 2025
2b6be9b
Merge remote-tracking branch 'upstream/main'
2chanhaeng Aug 8, 2025
ce8b649
Fix docs about `@fedify/next`
2chanhaeng Aug 8, 2025
4c5bf08
Set ESM configs for `@fedify/next`
2chanhaeng Aug 8, 2025
26d28e9
Support vary package managers
2chanhaeng Aug 9, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ node_modules/
repomix-output.xml
t.ts
t2.ts
.pnpm-store/
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { fedifyRequestHanlder } from "~/shared/integrate-fedify";
import { fedifyRequestHandler } from "~/shared/integrate-fedify";

export {
fedifyRequestHanlder as DELETE,
fedifyRequestHanlder as GET,
fedifyRequestHanlder as PATCH,
fedifyRequestHanlder as POST,
fedifyRequestHanlder as PUT,
fedifyRequestHandler as DELETE,
fedifyRequestHandler as GET,
fedifyRequestHandler as PATCH,
fedifyRequestHandler as POST,
fedifyRequestHandler as PUT,
};
4 changes: 2 additions & 2 deletions examples/next15-app-router/shared/integrate-fedify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ import {
import { keyPairsStore, relationStore } from "~/data/store";
import { revalidatePath } from "next/cache";

export const fedifyRequestHanlder = integrateFederation(() => {});
export const fedifyRequestHandler = integrateFederation(() => {});

const routePrefix = `/fedify-activity-handler`;

const federation = createFederation<void>({
const federation = createFederation({
kv: new MemoryKvStore(),
});

Expand Down
72 changes: 71 additions & 1 deletion packages/cli/src/init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const packagesMetaData: Record<`@fedify/${string}`, string> = {
"@fedify/amqp": metadata.version,
"@fedify/express": metadata.version,
"@fedify/h3": metadata.version,
"@fedify/nextjs": metadata.version,
};

const logger = getLogger(["fedify", "cli", "init"]);
Expand Down Expand Up @@ -85,7 +86,7 @@ const packageManagerLocations: Record<PackageManager, string | undefined> =
),
);

type WebFramework = "fresh" | "hono" | "express" | "nitro";
type WebFramework = "fresh" | "hono" | "express" | "nitro" | "next";

interface WebFrameworkInitializer {
command?: [string, ...string[]] | [...string[], string];
Expand Down Expand Up @@ -435,6 +436,75 @@ To start the server, run the following command:
Then, try look up an actor from your server:

${colors.bold(colors.green("fedify lookup http://localhost:3000/users/john"))}
`,
}),
},
next: {
label: "Next.js",
runtimes: ["node"],
init: (_, __, packageManager) => ({
label: "Next.js",
runtimes: ["node"],
command: [
"npx",
"create-next-app@canary",
".",
"--ts",
"--tailwind",
"--eslint",
"--app",
"--turbopack",
"--skip-install",
],
dependencies: {
"@fedify/nextjs": getLatestVersion("@fedify/nextjs"),
},
devDependencies: {
"@types/node": "^20.11.2",
},
federationFile: "federation/index.ts",
loggingFile: "logging.ts",
files: {
"middleware.ts": `
import { fedifyWith } from "@fedify/nextjs";
import federation from "./federation";

export default fedifyWith(federation)(
/*
function (request: Request) {
// If you need to handle other requests besides federation
// requests in middleware, you can do it here.
// If you handle only federation requests in middleware,
// you don't need this function.
return NextResponse.next();
},
*/
)

// This config needs because middleware process only requests with the
// "Accept" header matching the federation accept regex.
// More details: https://nextjs.org/docs/app/api-reference/file-conventions/middleware#config-object-optional
export const config = {
runtime: "nodejs",
matcher: [{
source: "/:path*",
has: [
{
type: "header",
key: "Accept",
value: ".*application\\\\/((jrd|activity|ld)\\\\+json|xrd\\\\+xml).*",
},
],
}],
};
`,
},
instruction: `
To start the server, run the following command:

${colors.bold(colors.green(packageManager + " run dev"))}
Then, try look up an actor from your server:
${colors.bold(colors.green("fedify lookup @john@localhost:3000"))}
`,
}),
},
Expand Down
67 changes: 67 additions & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"name": "@fedify/nextjs",
"version": "1.9.0",
"description": "Integrate Fedify with Next.js",
"keywords": [
"Fedify",
"ActivityPub",
"Fediverse",
"Next",
"Next.js"
],
"author": {
"name": "Chanhaeng Lee",
"email": "[email protected]",
"url": "https://chomu.dev"
},
"homepage": "https://fedify.dev/",
"repository": {
"type": "git",
"url": "git+https://github.com/fedify-dev/fedify.git",
"directory": "packages/nextjs"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/fedify-dev/fedify/issues"
},
"funding": [
"https://opencollective.com/fedify",
"https://github.com/sponsors/dahlia"
],
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
},
"./package.json": "./package.json"
},
"files": [
"dist/",
"package.json"
],
"dependencies": {
"x-forwarded-fetch": "^0.2.0"
},
"peerDependencies": {
"@fedify/fedify": "workspace:",
"next": "workspace:"
},
"devDependencies": {
"tsdown": "catalog:",
"typescript": "catalog:"
},
"scripts": {
"build": "tsdown",
"prepack": "tsdown",
"prepublish": "tsdown"
}
}
146 changes: 146 additions & 0 deletions packages/nextjs/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
/**
* Fedify with Next.js
* ================
*
* This module provides a [Next.js] middleware to integrate with the Fedify.
*
* [Next.js]: https://nextjs.org/
*
* @module
* @since 1.8.1
*/
import type { Federation, FederationFetchOptions } from "@fedify/fedify";
import { notFound } from "next/navigation";
import { NextResponse } from "next/server";
import { getXForwardedRequest } from "x-forwarded-fetch";

interface ContextDataFactory<TContextData> {
(request: Request):
| TContextData
| Promise<TContextData>;
}
type ErrorHandlers = Omit<FederationFetchOptions<unknown>, "contextData">;

/**
* Wrapper function for Next.js middleware to integrate with the
* {@link Federation} object.
*
* @template TContextData A type of the context data for the
* {@link Federation} object.
* @param {Federation<TContextData>} federation A {@link Federation} object
* to integrate with Next.js.
* @param {ContextDataFactory<TContextData>} contextDataFactory A function
* to create a context data for the
* {@link Federation} object.
* @param {Partial<ErrorHandlers>} errorHandlers A set of error handlers to
* handle errors during the federation fetch.
* @returns A Next.js middleware function to integrate with the
* {@link Federation} object.
*
* @example
* ```ts
* import { fedifyWith } from "@fedify/next";
* import { federation } from "./federation";
*
* export default fedifyWith(federation)(
* function (request: Request) {
* // You can add custom logic here for other requests
* // except federation requests. If there is no custom logic,
* // you can omit this function.
* }
* )
*
* // This config makes middleware process only requests with the
* // "Accept" header matching the federation accept regex.
* // More details: https://nextjs.org/docs/app/api-reference/file-conventions/middleware#config-object-optional.
* export const config = {
* runtime: "nodejs",
* matcher: [{
* source: "/:path*",
* has: [
* {
* type: "header",
* key: "Accept",
* value: ".*application\\/((jrd|activity|ld)\\+json|xrd\\+xml).*",
* },
* ],
* }],
* };
* ```
*/
export const fedifyWith = <TContextData>(
federation: Federation<TContextData>,
contextDataFactory?: ContextDataFactory<TContextData>,
errorHandlers?: Partial<ErrorHandlers>,
) =>
(
middleware: (request: Request) => unknown =
((_: Request) => NextResponse.next()),
): (request: Request) => unknown =>
async (request: Request) => {
if (hasFederationAcceptHeader(request)) {
return await integrateFederation(
federation,
contextDataFactory,
errorHandlers,
)(request);
}
return await middleware(request);
};

/**
* Check if the request has the "Accept" header matching the federation
* accept regex.
*
* @param {Request} request The request to check.
* @returns {boolean} `true` if the request has the "Accept" header matching
* the federation accept regex, `false` otherwise.
*/
export const hasFederationAcceptHeader = (request: Request): boolean => {
const acceptHeader = request.headers.get("Accept");
// Check if the Accept header matches the federation accept regex.
// If the header is not present, return false.
return acceptHeader ? FEDERATION_ACCEPT_REGEX.test(acceptHeader) : false;
};
const FEDERATION_ACCEPT_REGEX =
/.*application\/((jrd|activity|ld)\+json|xrd\+xml).*/;

/**
* Create a Next.js handler to integrate with the {@link Federation} object.
*
* @template TContextData A type of the context data for the
* {@link Federation} object.
* @param {Federation<TContextData>} federation A {@link Federation} object
* to integrate with Next.js.
* @param {ContextDataFactory<TContextData>} contextDataFactory A function
* to create a context data for the
* {@link Federation} object.
* @param {Partial<ErrorHandlers>} errorHandlers A set of error handlers to
* handle errors during the federation fetch.
* @returns A Next.js handler.
*/
export function integrateFederation<TContextData>(
federation: Federation<TContextData>,
contextDataFactory: ContextDataFactory<TContextData> = () =>
undefined as TContextData,
errorHandlers?: Partial<ErrorHandlers>,
) {
return async (request: Request) => {
const forwardedRequest = await getXForwardedRequest(request);
const contextData = await contextDataFactory(forwardedRequest);
return await federation.fetch(
forwardedRequest,
{
contextData,
onNotFound: notFound,
onNotAcceptable,
...errorHandlers,
},
);
};
}
const onNotAcceptable = () =>
new Response("Not acceptable", {
status: 406,
headers: { "Content-Type": "text/plain", Vary: "Accept" },
});
8 changes: 8 additions & 0 deletions packages/nextjs/tsdown.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from "tsdown";

export default defineConfig({
entry: ["src/index.ts"],
dts: true,
platform: "node",
format: ["commonjs", "esm"],
});
Loading
Loading