0
-pages
-----admin
+++++++++index.js

How to create a middleware so that if user is not logged in to be redirected in a page?

1 Answer 1

1

At the admin folder, you create a file "_middleware.js".

import { NextRequest, NextResponse } from "next/server";
import { getToken } from "next-auth/jwt";

export async function middleware(req, res) {
  const secret_key = process.env.SECRET_KEY;

  if (!secret_key) {
    return new Response("Blocked for Server Problems", { status: 451 });
  }

  const session = await getToken({ req, secret: secret_key });

  if (!session) {
    return NextResponse.redirect("/api/auth/signin");
  }
  return NextResponse.next();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.