improved nextjs/remix adapters and docs, confirmed remix ssr working

This commit is contained in:
dswbx
2024-11-26 11:15:38 +01:00
parent eea76ebc28
commit 9d896a6ab1
23 changed files with 275 additions and 209 deletions

View File

@@ -5,17 +5,19 @@ import { omit } from "lodash-es";
import { MediaApi } from "media/api/MediaApi";
import { SystemApi } from "modules/SystemApi";
export type TApiUser = object;
declare global {
interface Window {
__BKND__: {
user?: any;
user?: TApiUser;
};
}
}
export type ApiOptions = {
host: string;
user?: object;
user?: TApiUser;
token?: string;
headers?: Headers;
key?: string;
@@ -24,7 +26,7 @@ export type ApiOptions = {
export class Api {
private token?: string;
private user?: object;
private user?: TApiUser;
private verified = false;
private token_transport: "header" | "cookie" | "none" = "header";
@@ -111,6 +113,10 @@ export class Api {
};
}
getUser(): TApiUser | null {
return this.user || null;
}
private buildApis() {
const baseParams = {
host: this.options.host,

View File

@@ -5,8 +5,6 @@ import { serveStatic } from "hono/cloudflare-workers";
import type { BkndConfig, CfBkndModeCache } from "../index";
// @ts-ignore
//import manifest from "__STATIC_CONTENT_MANIFEST";
import _html from "../../static/index.html";
type Context = {

View File

@@ -1,3 +1,4 @@
import type { IncomingMessage } from "node:http";
import type { App, CreateAppConfig } from "bknd";
export type CfBkndModeCache<Env = any> = (env: Env) => {
@@ -35,3 +36,27 @@ export type BkndConfigJson = {
port?: number;
};
};
export function nodeRequestToRequest(req: IncomingMessage): Request {
let protocol = "http";
try {
protocol = req.headers["x-forwarded-proto"] as string;
} catch (e) {}
const host = req.headers.host;
const url = `${protocol}://${host}${req.url}`;
const headers = new Headers();
for (const [key, value] of Object.entries(req.headers)) {
if (Array.isArray(value)) {
headers.append(key, value.join(", "));
} else if (value) {
headers.append(key, value);
}
}
const method = req.method || "GET";
return new Request(url, {
method,
headers
});
}

View File

@@ -0,0 +1,24 @@
import { withApi } from "bknd/adapter/nextjs";
import type { InferGetServerSidePropsType } from "next";
import dynamic from "next/dynamic";
export const getServerSideProps = withApi(async (context) => {
return {
props: {
user: context.api.getUser()
}
};
});
export function adminPage() {
const Admin = dynamic(() => import("bknd/ui").then((mod) => mod.Admin), { ssr: false });
const ClientProvider = dynamic(() => import("bknd/ui").then((mod) => mod.ClientProvider));
return (props: InferGetServerSidePropsType<typeof getServerSideProps>) => {
if (typeof document === "undefined") return null;
return (
<ClientProvider user={props.user}>
<Admin />
</ClientProvider>
);
};
}

View File

@@ -1 +1,2 @@
export * from "./nextjs.adapter";
export * from "./AdminPage";

View File

@@ -1,5 +1,36 @@
import { App, type CreateAppConfig } from "bknd";
import type { IncomingMessage, ServerResponse } from "node:http";
import { Api, App, type CreateAppConfig } from "bknd";
import { isDebug } from "bknd/core";
import { nodeRequestToRequest } from "../index";
type GetServerSidePropsContext = {
req: IncomingMessage;
res: ServerResponse;
params?: Params;
query: any;
preview?: boolean;
previewData?: any;
draftMode?: boolean;
resolvedUrl: string;
locale?: string;
locales?: string[];
defaultLocale?: string;
};
export function createApi({ req }: GetServerSidePropsContext) {
const request = nodeRequestToRequest(req);
//console.log("createApi:request.headers", request.headers);
return new Api({
host: new URL(request.url).origin,
headers: request.headers
});
}
export function withApi<T>(handler: (ctx: GetServerSidePropsContext & { api: Api }) => T) {
return (ctx: GetServerSidePropsContext & { api: Api }) => {
return handler({ ...ctx, api: createApi(ctx) });
};
}
function getCleanRequest(req: Request) {
// clean search params from "route" attribute

View File

@@ -0,0 +1,19 @@
import { Suspense, lazy, useEffect, useState } from "react";
export function adminPage() {
const Admin = lazy(() => import("bknd/ui").then((mod) => ({ default: mod.Admin })));
return () => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (typeof window === "undefined") return;
setLoaded(true);
}, []);
if (!loaded) return null;
return (
<Suspense>
<Admin />
</Suspense>
);
};
}

View File

@@ -1 +1,2 @@
export * from "./remix.adapter";
export * from "./AdminPage";

View File

@@ -257,11 +257,15 @@ export class Authenticator<Strategies extends Record<string, Strategy> = Record<
return c.json(data);
}
const referer = new URL(redirect ?? c.req.header("Referer") ?? "/");
const successPath = "/";
const successUrl = new URL(c.req.url).origin + successPath.replace(/\/+$/, "/");
const referer = new URL(redirect ?? c.req.header("Referer") ?? successUrl);
if ("token" in data) {
// @todo: add config
await this.setAuthCookie(c, data.token);
return c.redirect("/");
// can't navigate to "/" doesn't work on nextjs
return c.redirect(successUrl);
}
let message = "An error occured";

View File

@@ -117,6 +117,7 @@ export class AdminController implements ClassController {
let script: string | undefined;
let css: string[] = [];
// @todo: check why nextjs imports manifest, it's not required
if (isProd) {
const manifest: Manifest = this.options.viteManifest
? this.options.viteManifest

View File

@@ -1,4 +1,5 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { TApiUser } from "Api";
import { createContext, useContext, useEffect, useState } from "react";
import { useBkndWindowContext } from "ui/client/BkndProvider";
import { AppQueryClient } from "./utils/AppQueryClient";
@@ -20,7 +21,7 @@ export const ClientProvider = ({
children,
baseUrl,
user
}: { children?: any; baseUrl?: string; user?: object }) => {
}: { children?: any; baseUrl?: string; user?: TApiUser | null }) => {
const [actualBaseUrl, setActualBaseUrl] = useState<string | null>(null);
const winCtx = useBkndWindowContext();