Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/next 12 2 #131

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion starters/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@
"lodash": "^4.17.19",
"mongoose": "6",
"nanoid": "^3.1.25",
"next": "^12.1.6",
"next": "latest",
"next-connect": "^0.9.1",
"next-i18next": "^8.10.0",
"next-mdx-remote": "3",
Expand Down
22 changes: 22 additions & 0 deletions starters/next/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextFetchEvent, NextRequest } from "next/server";
import {
debugMatcher,
debugMiddleware,
} from "~/vulcan-demo/edge-middlewares/debugMiddleware";
import {
megaparamMatcher,
megaParamMiddleware,
} from "~/vulcan-demo/edge-middlewares/megaparamMiddleware";

export function middleware(req: NextRequest, event: NextFetchEvent) {
// TODO: how to reuse the "debugMatcher" which is not really a regex?
if (req.url.match(/debug/)) {
return debugMiddleware(req, event);
}
if (req.url.match(/megaparam-demo/)) {
return megaParamMiddleware(req, event);
}
}
export const config = {
matchers: [debugMatcher], //, megaparamMatcher],
};
28 changes: 28 additions & 0 deletions starters/next/src/pages/api/vn/examples/megaparam-form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NextRequest, NextResponse } from "next/server";

export default async (req: NextRequest) => {
// TODO: this doesn't work because we cannot use a POST request here
// otherwise we fail to redirect using a GET afterwards
// const formData = await req.formData();
// const theme = formData.get("theme")?.toString();
// const company = formData.get("company")?.toString();
const url = new URL(req.url);
const theme = url.searchParams.get("theme");
const company = url.searchParams.get("company");

// Redirect back to the page with an absolute URL
const pageUrl = new URL("/vn/examples/megaparam-demo", req.url);
const res = NextResponse.redirect(pageUrl);

if (theme && ["light", "dark"].includes(theme)) {
res.cookies.set("theme", theme);
}
if (company) {
res.cookies.set("my_company", company);
}
return res;
};

export const config = {
runtime: "experimental-edge",
};
30 changes: 0 additions & 30 deletions starters/next/src/pages/vn/examples/[M]/_middleware.ts

This file was deleted.

13 changes: 10 additions & 3 deletions starters/next/src/pages/vn/examples/[M]/megaparam-demo.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// NOTE: after Next 12.2 update, the corresponding middleware now lives in
// src/vulcan-demo/edge-middlewares/megaparamMiddleware.ts
import { GetStaticPaths } from "next";
import { GetStaticProps, InferGetStaticPropsType } from "next";
import { useRouter } from "next/dist/client/router";
// import { useRouter } from "next/router";

/**
* Run the server and open
Expand All @@ -10,7 +12,7 @@ export const MegaparamDemo = ({
params,
}: InferGetStaticPropsType<typeof getStaticProps>) => {
const { theme, company } = params;
const router = useRouter();
//const router = useRouter();
return (
<div
style={{
Expand Down Expand Up @@ -41,14 +43,19 @@ export const MegaparamDemo = ({
</a>
</p>
<form
action="/api/vn/examples/megaparam-form"
// If you use a POST method, you won't be able to redirect back to the form using a edge API handler
//method="POST"
/*
Old JS version
onSubmit={(evt) => {
evt.preventDefault();
const theme = evt.target["theme"]?.value;
const company = evt.target["company"]?.value;
(window as any).cookieStore.set("company", company);
(window as any).cookieStore.set("theme", theme);
router.reload();
}}
}}*/
>
<label htmlFor="theme">Pick a theme:</label>
<select id="theme" name="theme" defaultValue={theme}>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";

export function middleware(req: NextRequest, ev: NextFetchEvent) {
export const debugMatcher = "/vn/debug/:path*";

export function debugMiddleware(req: NextRequest, ev: NextFetchEvent) {
// @see https://nextjs.org/docs/messages/middleware-relative-urls
if (
process.env.NODE_ENV === "production" &&
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { NextFetchEvent, NextRequest, NextResponse } from "next/server";

import { encode } from "~/pages/vn/examples/[M]/megaparam-demo";
export const megaparamMatcher = "/vn/examples/:M/megaparam-demo";
// @see https://blog.vulcanjs.org/render-anything-statically-with-next-js-and-the-megaparam-4039e66ffde
export function megaParamMiddleware(req: NextRequest, event: NextFetchEvent) {
// get the current params from the cookies, eg theme
// you can also get them from headers, url, route params...
const theme = req.cookies.get("theme") || "light";
if (!["light", "dark"].includes(theme)) {
throw new Error(
`Valid themes are light and dark, received ${theme}. Clear your cookies and try again.`
);
}
const company = req.cookies.get("company") || "Unknown_company";
// Here, you could run some checks, like
// verifying that current user can actually access this company
// and that the theme is valid
const isValid = true;
if (!isValid) {
throw new Error("User cannot access company");
}
// convert to a megaparam
const megaparam = encode({
theme,
company,
});
// This patterns guarantee that the URL is absolute
req.nextUrl.pathname = `/vn/examples/${megaparam}/megaparam-demo`;
const res = NextResponse.rewrite(req.nextUrl);
return res;
}
Loading