clean way to protect page and redirect

What is the clean way to dont allow not authenticated user access to the page and instead redirect him to sign in?
5 Replies
iDarkLightning
For checking it clientside (not in gssp), I tend to just follow https://next-auth.js.org/getting-started/client#require-session
Client API | NextAuth.js
The NextAuth.js client library makes it easy to interact with sessions from React applications.
noctate
noctateOP2y ago
thx
Gaurang
Gaurang2y ago
I've been using the middleware solution for awhile and it's been working pretty well for me. It's extended from the logic in the docs: https://nextjs.org/docs/advanced-features/middleware
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";

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

export async function middleware(req: NextRequest) {
//token will exist if user is logged in
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });

const { pathname } = req.nextUrl;

const whitelist: string[] = ['api/auth', '/'];

if (whitelist.includes(pathname) || token) {
return NextResponse.next();
}

//redirect them to login if they don't have token and are requesting a protected route
const protectedRoutes: string[] = ["/admin"];

const isProtectedRoute = protectedRoutes.every((path) => path === pathname);

if (!token && isProtectedRoute) {
console.log("redirect to login middleware", null);
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
});
}

export const config = {
matcher: "/",
};
import { getToken } from "next-auth/jwt";
import { NextResponse } from "next/server";

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

export async function middleware(req: NextRequest) {
//token will exist if user is logged in
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });

const { pathname } = req.nextUrl;

const whitelist: string[] = ['api/auth', '/'];

if (whitelist.includes(pathname) || token) {
return NextResponse.next();
}

//redirect them to login if they don't have token and are requesting a protected route
const protectedRoutes: string[] = ["/admin"];

const isProtectedRoute = protectedRoutes.every((path) => path === pathname);

if (!token && isProtectedRoute) {
console.log("redirect to login middleware", null);
return NextResponse.redirect(new URL("/auth/signin", req.url));
}
});
}

export const config = {
matcher: "/",
};
Advanced Features: Middleware | Next.js
Learn how to use Middleware to run code before a request is completed.
Unknown User
Unknown User2y ago
Message Not Public
Sign In & Join Server To View
jack
jack2y ago
honestly not sure if this is a good practice or not, but i found doing it per page in getServerSideProps nicer than doing some sort of array of protected pages in a middleware, and i wrote this helper function https://github.com/jackbisceglia/mmapicks/blob/main/src/utils/ssr/authenticateUserServerSide.ts then i just call it in getServerSideProps as such
export const getServerSideProps: GetServerSideProps = async (ctx) =>
authenticateUserServerSide(ctx);
export const getServerSideProps: GetServerSideProps = async (ctx) =>
authenticateUserServerSide(ctx);
if i need more than just protection in my serversideprops logic, i just pass a callback which returns props the same way you do in getServerSideProps
export const getServerSideProps: GetServerSideProps = (ctx) =>
authenticateUserServerSide(ctx, async (auth) => {
// more logic here
return {
props: {
// props here
}
}
});

export default GroupPage;
export const getServerSideProps: GetServerSideProps = (ctx) =>
authenticateUserServerSide(ctx, async (auth) => {
// more logic here
return {
props: {
// props here
}
}
});

export default GroupPage;
Want results from more Discord servers?
Add your server