Skip to content

Commit acfea28

Browse files
committed
feat: enhance the readme for better usage experience #2
1 parent e9d779a commit acfea28

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

README.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,9 +111,17 @@ It also takes an object with the following properties:
111111
Here's an example of constructing the middleware:
112112

113113
```ts
114+
import env from "@/env";
115+
import { NextResponse } from "next/server";
116+
import { isNotLoggedIn, isLoggedIn, isAdmin, isOwnWorkspace } from "@/lib/rules";
117+
import { routes } from "@/lib/link$";
118+
import type { Data } from "@/types";
119+
import Middleware from "@triyanox/next-middleware";
120+
114121
const middleware = new Middleware<typeof routes, Data>({
115122
fetch: async (req) => {
116123
// Fetch and return the data for route checks
124+
// call an API or a serverless function/db to fetch the data (note that the middleware file is not running on a node.js environment so you can't use things like prisma, mongoose, etc. directly in my case I make an API call to fetch the data)
117125
},
118126
rules: {
119127
"/login": [isNotLoggedIn],
@@ -123,6 +131,11 @@ const middleware = new Middleware<typeof routes, Data>({
123131
authPaths: ["/login", "/dashboard"],
124132
onError: async (req) => {
125133
// Handle errors and redirects
134+
const path = new URL(req.url).pathname;
135+
if (path === "/login") {
136+
return NextResponse.next();
137+
}
138+
return NextResponse.redirect(env.NEXT_PUBLIC_URL + "/login");
126139
},
127140
});
128141
```

0 commit comments

Comments
 (0)