Merged in fix/rewrite-nexturl (pull request #73)

fix: split middleware in two, authed and public

Approved-by: Michael Zetterberg
This commit is contained in:
Simon.Emanuelsson
2024-03-27 10:23:11 +00:00
committed by Michael Zetterberg
3 changed files with 82 additions and 57 deletions

View File

@@ -1,4 +1,4 @@
import { NextResponse } from "next/server" import { NextRequest, NextResponse } from "next/server"
import { auth } from "@/auth" import { auth } from "@/auth"
@@ -6,26 +6,48 @@ import { findLocale } from "@/constants/locales"
import { pageNames } from "@/constants/myPages" import { pageNames } from "@/constants/myPages"
import { apiAuthPrefix } from "@/routes/api" import { apiAuthPrefix } from "@/routes/api"
// import { publicRoutes } from "@/routes/public"
import { protectedRoutes } from "@/routes/protected" import { protectedRoutes } from "@/routes/protected"
export default auth(async function middleware(request) { import type { NextAuthRequest } from "next-auth"
const { nextUrl } = request
const isLoggedIn = !!request.auth
const isApiRoute = nextUrl.pathname.startsWith(apiAuthPrefix) export async function publiceMiddleware(request: NextRequest) {
if (isApiRoute) { const { nextUrl } = request
const locale = findLocale(nextUrl.pathname)
if (nextUrl.pathname.startsWith(`/${locale}/login`)) {
return NextResponse.next() return NextResponse.next()
} }
const locale = findLocale(nextUrl.pathname) const contentType = "currentContentPage"
if (!locale) { const pathNameWithoutLocale = nextUrl.pathname.replace(`/${locale}`, "")
//return <LocalePicker /> const searchParams = new URLSearchParams(request.nextUrl.searchParams)
return Response.json("Not found!!!", { status: 404 })
if (request.nextUrl.pathname.includes("preview")) {
searchParams.set("uri", pathNameWithoutLocale.replace("/preview", ""))
return NextResponse.rewrite(
new URL(`/${locale}/preview-current?${searchParams.toString()}`, nextUrl)
)
} }
const isProtectedRoute = protectedRoutes.includes(nextUrl.pathname) searchParams.set("uri", pathNameWithoutLocale)
if (isProtectedRoute) { switch (contentType) {
case "currentContentPage":
return NextResponse.rewrite(
new URL(
`/${locale}/current-content-page?${searchParams.toString()}`,
nextUrl
)
)
}
// Unreachable atm
return NextResponse.next()
}
async function authedMiddlewareFunction(request: NextAuthRequest) {
const { nextUrl } = request
const locale = findLocale(nextUrl.pathname)!
const isLoggedIn = !!request.auth
if (isLoggedIn) { if (isLoggedIn) {
/** /**
* Temporary hard rewrite to my pages * Temporary hard rewrite to my pages
@@ -42,43 +64,39 @@ export default auth(async function middleware(request) {
} }
} }
if (nextUrl.pathname.startsWith(`/${locale}/login`)) { const authedMiddleware = auth(authedMiddlewareFunction)
export async function middleware(request: NextRequest) {
const { nextUrl } = request
const isApiRoute = nextUrl.pathname.startsWith(apiAuthPrefix)
if (isApiRoute) {
return NextResponse.next() return NextResponse.next()
} }
// const isPublicRoute = publicRoutes.includes(nextUrl.pathname) const locale = findLocale(nextUrl.pathname)
// if (!isLoggedIn && !isPublicRoute) { if (!locale) {
// return NextResponse.redirect(new URL(`/${locale}/login`, nextUrl)) //return <LocalePicker />
// } return Response.json("Not found!!!", { status: 404 })
//const contentType = data.response.meta.contentType;
const contentType = "currentContentPage"
const pathNameWithoutLocale = nextUrl.pathname.replace(`/${locale}`, "")
const searchParams = new URLSearchParams(request.nextUrl.searchParams)
if (request.nextUrl.pathname.includes("preview")) {
searchParams.set("uri", pathNameWithoutLocale.replace("/preview", ""))
return NextResponse.rewrite(
new URL(
`/${locale}/preview-current?${searchParams.toString()}`,
request.url
)
)
} }
searchParams.set("uri", pathNameWithoutLocale) const isProtectedRoute = protectedRoutes.includes(nextUrl.pathname)
switch (contentType) { if (isProtectedRoute) {
case "currentContentPage": /**
return NextResponse.rewrite( * AppRouteHandlerFnContext is the context that is passed to the handler as the
new URL( * second argument.
`/${locale}/current-content-page?${searchParams.toString()}`, *
request.url * type AppRouteHandlerFnContext = {
) * params?: Record<string, string | string[]>
) * }
*
* We don't need it so just pass an empty object
*/
return authedMiddleware(request, {})
} else {
return publiceMiddleware(request)
}
} }
return NextResponse.next()
})
// See "Matching Paths" below to learn more // See "Matching Paths" below to learn more
export const config = { export const config = {

View File

@@ -1,2 +0,0 @@
/* Unauthenticated routes */
export const publicRoutes: string[] = ["/"]

9
types/auth.d.ts vendored
View File

@@ -1,4 +1,5 @@
import "next-auth" import "next-auth"
import type { NextRequest } from "next/server"
// Module augmentation // Module augmentation
// https://authjs.dev/getting-started/typescript#popular-interfaces-to-augment // https://authjs.dev/getting-started/typescript#popular-interfaces-to-augment
@@ -21,6 +22,14 @@ declare module "next-auth" {
* Returned by `useSession`, `auth`, contains information about the active session. * Returned by `useSession`, `auth`, contains information about the active session.
*/ */
interface Session {} interface Session {}
/**
* NextAuthRequest isn't exported by next-auth so we declare a copy
* of how they do it to support or switch in middleware.ts
*/
interface NextAuthRequest extends NextRequest {
auth: Session | null
}
} }
declare module "next-auth/jwt" { declare module "next-auth/jwt" {