Next.js Discord

Discord Forum

protected routes

Answered
American Chinchilla posted this in #help-forum
Open in Discord
American ChinchillaOP
How to create a protected route that only user who is authenticated can visit without copy pasting code for each page to check whether user is authed

For example how to make all pages under /dashboard route protected?
Im using nextjs 13 app dir
Answered by Yi Lon Ma
import { type NextRequest, NextResponse } from 'next/server';

const PUBLIC_ROUTES = ['/sign-in', '/sign-up'];

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if (
    request.nextUrl.pathname.startsWith('/profile') &&
    request.nextUrl.pathname.replace(/\/profile\/(.*)/gm, '') === ''
  )
    return;
  if (PUBLIC_ROUTES.includes(request.nextUrl.pathname)) {
    if (request.cookies.get('token')?.value) {
      return NextResponse.redirect(new URL('/', request.url));
    }
    return;
  } else if (!request.cookies.get('token')?.value)
    return NextResponse.redirect(new URL('/sign-up', request.url));
}

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)'],
};


I am currently using this middleware and it works as expected
View full answer

7 Replies

@Yi Lon Ma use middleware
American ChinchillaOP
Could you provide me an example how to set up this
@American Chinchilla Could you provide me an example how to set up this
import { type NextRequest, NextResponse } from 'next/server';

const PUBLIC_ROUTES = ['/sign-in', '/sign-up'];

// This function can be marked `async` if using `await` inside
export function middleware(request: NextRequest) {
  if (
    request.nextUrl.pathname.startsWith('/profile') &&
    request.nextUrl.pathname.replace(/\/profile\/(.*)/gm, '') === ''
  )
    return;
  if (PUBLIC_ROUTES.includes(request.nextUrl.pathname)) {
    if (request.cookies.get('token')?.value) {
      return NextResponse.redirect(new URL('/', request.url));
    }
    return;
  } else if (!request.cookies.get('token')?.value)
    return NextResponse.redirect(new URL('/sign-up', request.url));
}

export const config = {
  matcher: ['/((?!.*\\..*|_next).*)', '/(api|trpc)(.*)'],
};


I am currently using this middleware and it works as expected
Answer
American ChinchillaOP
Okay thanks ill look into it soon
Only thing how does it gets registered do i just make middleware.ts file in app dir and export middleware function
American ChinchillaOP
ah okay and it just works