如果用户未经身份验证,则重定向到登录页面。

huangapple go评论77阅读模式
英文:

Redirect to login page if the user is unauthenticated

问题

我的中间件在重定向到登录页面后崩溃的原因是什么?

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

// 如果在内部使用await,则可以将此函数标记为“async”
export async function middleware(request: NextRequest) {
  const HAS_COOKIE = isAuthenticated();
  const hostname = request.nextUrl.hostname;
  if (HAS_COOKIE) {
    if (request.nextUrl.pathname.startsWith("/auth")) {
      return NextResponse.redirect("http://localhost:3000/feed");
    }
    return NextResponse.next();
  } else {
    return NextResponse.redirect("http://localhost:3000/auth/signin");
  }
}
export const config = {
  matcher: [
    /*
     * 匹配所有请求路径,除了以下路径开头的请求:
     * - api(API路由)
     * - _next/static(静态文件)
     * - _next/image(图像优化文件)
     * - favicon.ico(favicon文件)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

此代码应在未检测到任何cookie时进行重定向。

英文:

Why my middleware is crashing after redirecting to my login page?

import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";

// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest) {
  const HAS_COOKIE = isAuthenticated();
  const hostname = request.nextUrl.hostname;
  if (HAS_COOKIE) {
    if (request.nextUrl.pathname.startsWith("/auth")) {
      return NextResponse.redirect("http://localhost:3000/feed");
    }
    return NextResponse.next();
  } else {
    return NextResponse.redirect("http://localhost:3000/auth/signin");
  }
}
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

This code should redirect if it doesn't detect any cookies.

答案1

得分: 0

尝试使用const HAS_COOKIE = request.cookies.has("token");

你正在调用一个不存在的函数“isAuthenticated()”。

英文:

try using const HAS_COOKIE = request.cookies.has("token");

you are calling a function "isAuthenticated()" which does not exist

答案2

得分: 0

我所做的是创建一个私有路由数组,然后在我的代码中添加一个条件:

// 导入必要的模块
import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";

// 循环处理
const privateRoutes = ["/feed", "/messages", "/search"];
// 如果在此函数内部使用了`await`,可以将其标记为`async`
export async function middleware(request: NextRequest, event: NextFetchEvent) {
  const hostname = request.nextUrl.origin;
  const pathname = request.nextUrl.pathname;
  const HAS_COOKIE = isAuthenticated(); // 这只是一个获取 cookie 的代码

  // 已认证
  if (HAS_COOKIE) {
    if (pathname.startsWith("/auth")) {
      return NextResponse.redirect(`${hostname}/feed`);
    }
    return NextResponse.next();
  } else {
    if (privateRoutes.includes(pathname)) {
      return NextResponse.redirect(`${hostname}/auth/signin`);
    }
    return NextResponse.next();
  }
}
export const config = {
  matcher: [
    /*
     * 匹配所有请求路径,除了以下开头的路径:
     * - api (API 路由)
     * - _next/static (静态文件)
     * - _next/image (图片优化文件)
     * - favicon.ico (网站图标文件)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};
英文:

What I did was to create an array of private routes and then add a condition in my code

import type { NextFetchEvent, NextRequest } from "next/server";
import { NextResponse } from "next/server";

// loop this
const privateRoutes = ["/feed", "/messages", "/search"];
// This function can be marked `async` if using `await` inside
export async function middleware(request: NextRequest, event: NextFetchEvent) {
  const hostname = request.nextUrl.origin;
  const pathname = request.nextUrl.pathname;
  const HAS_COOKIE = isAuthenticated() // this is just a code that gets the cookie
  // authenticated
  if (HAS_COOKIE) {
    if (pathname.startsWith("/auth")) {
      return NextResponse.redirect(`${hostname}/feed`);
    }
    return NextResponse.next();
  } else {
    if (privateRoutes.includes(pathname)) {
      return NextResponse.redirect(`${hostname}/auth/signin`);
    }
    return NextResponse.next();
  }
}
export const config = {
  matcher: [
    /*
     * Match all request paths except for the ones starting with:
     * - api (API routes)
     * - _next/static (static files)
     * - _next/image (image optimization files)
     * - favicon.ico (favicon file)
     */
    "/((?!api|_next/static|_next/image|favicon.ico).*)",
  ],
};

huangapple
  • 本文由 发表于 2023年1月9日 17:37:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055388.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定