Skip to content

Commit

Permalink
Fix middleware with /dashboard routes & add custom prefix.
Browse files Browse the repository at this point in the history
  • Loading branch information
pheralb committed Jan 10, 2024
1 parent f499801 commit 50880d4
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 38 deletions.
3 changes: 3 additions & 0 deletions src/app/api/url/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export const GET = async (req: NextRequest) => {
);
}

// Check if page exists:


// Get data from query:
const data = (await db.link.findFirst({
where: {
Expand Down
73 changes: 37 additions & 36 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,68 +1,69 @@
import type { NextRequest } from "next/server";

import NextAuth from "next-auth";
import authConfig from "auth.config";

// App Routes:
// Check src/routes.ts.
import {
DEFAULT_LOGIN_REDIRECT_URL,
apiAuthPrefix,
authRoutes,
dashboardRoutesPrefix,
publicRoutes,
} from "./routes";

// Auth Config:
const { auth } = NextAuth(authConfig);

const middleware = async (req: NextRequest, isLoggedIn: boolean) => {
const { nextUrl } = req;
try {
const { nextUrl } = req;
const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const isDashboardRoute = nextUrl.pathname.startsWith(dashboardRoutesPrefix);
const slugRoute = req.nextUrl.pathname.split("/").pop();

const isApiAuthRoute = nextUrl.pathname.startsWith(apiAuthPrefix);
const isPublicRoute = publicRoutes.includes(nextUrl.pathname);
const isAuthRoute = authRoutes.includes(nextUrl.pathname);
const slugRoute = req.nextUrl.pathname.split("/").pop();

// Is Api Route:
if (isApiAuthRoute) {
return null;
}
// Is Api Route:
if (isApiAuthRoute) {
return null;
}

// Is Auth Route. First, check is authenticated:
if (isAuthRoute) {
if (isLoggedIn) {
// Is Auth Route. First, check is authenticated:
if (isAuthRoute && isLoggedIn) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT_URL, nextUrl));
}
return null;
}

// Protected routes:
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/login", nextUrl));
}
// Protected routes:
if (!isLoggedIn && !isPublicRoute) {
return Response.redirect(new URL("/login", nextUrl));
}

// Now, check ``slug`` route.
// If does not exist, redirect to main page.
const data = await fetch(`${req.nextUrl.origin}/api/url?slug=${slugRoute}`);
// Check ``slug`` route.
if (!isDashboardRoute && !isAuthRoute && !isApiAuthRoute) {
const data = await fetch(
`${req.nextUrl.origin}/api/url?slug=${slugRoute}`,
);

if (data.status === 404) {
return Response.redirect(req.nextUrl.origin);
}
if (data.status === 404) {
console.log(`Slug not found: ${slugRoute}`);
return null;
}

const dataToJson = await data.json();
const dataToJson = await data.json();

if (data?.url) {
return Response.redirect(new URL(dataToJson.url as string).toString());
}
if (dataToJson.url) {
return Response.redirect(new URL(dataToJson.url as string).toString());
}
}

return null;
return null;
} catch (error) {
console.error("Error in middleware:", error);
return new Response("Internal Server Error", { status: 500 });
}
};

export default auth((req) => middleware(req, !!req.auth));

export const config = {
matcher: [
"/",
"/((?!api/|_next/|_proxy/|_static|_vercel|[\\w-]+\\.\\w+).*)",
"/s/:slug*",
],
Expand Down
6 changes: 4 additions & 2 deletions src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,12 @@ export const authRoutes = [
];

/**
* These routes require authentication and are only accessible to admins.
* These routes are used for the dashboard.
* Required for authentication.
* Only type the prefix.
* @type {string[]}
*/
export const protectedRoutes = [];
export const dashboardRoutesPrefix = "/dashboard";

/**
* These prefix for API authentication routes.
Expand Down

0 comments on commit 50880d4

Please sign in to comment.