#Protecting my routes

1 messages · Page 1 of 1 (latest)

torn oxide
#

Hi I am using next js 14 with aws amplify for authentication. I guess aws amplify had some updates so you will be not up to date. I am using the method getCurrentUser() to get the session of the current user.
In my middleware I want only allow access to / route for unauthenticated access. If the user is authenticated I would allow any route which is available.
The method getCurrentUser will give me the following back if i am unauthenticated
Promise { <state>: "pending" }

<state>: "rejected"

<reason>: UserUnAuthenticatedException: User needs to be authenticated to call this API.
​​
columnNumber: 9
​​
constructor: class AuthError { constructor(params) }
​​
message: "User needs to be authenticated to call this API."
​​
name: "UserUnAuthenticatedException"
​​
recoverySuggestion: "Sign in before calling this API again."

and this when I am authenticated
Promise { <state>: "pending" }

<state>: "fulfilled"

<value>: Object { username: "73840872-f081-7095-b89f-2095df12f574", userId: "73840872-f081-7095-b89f-2095df12f574", signInDetails: {…} }
​​
signInDetails: Object { loginId: "a@gmail.com", authFlowType: "USER_SRP_AUTH" }
​​​
authFlowType: "USER_SRP_AUTH"
​​​
loginId: "a@gmail.com"
​​​
<prototype>: Object { … }
​​
userId: "73840872-f081-7095-b89f-2095df12f574"
I would like to extend my middleware with the protected routes etc.

import { getCurrentUser } from 'aws-amplify/auth';
import createMiddleware from 'next-intl/middleware';
import { locales, localePrefix } from '../i18n/navigation';

export default createMiddleware({
  defaultLocale: 'nl',
  localePrefix,
  locales,
  localeDetection: true,
});

export const config = {
  // Skip all paths that should not be internationalized. This example skips
  // certain folders and all pathnames with a dot (e.g. favicon.ico)
  matcher: ['/((?!api|_next|_vercel|.*\\..*).*)'],
};

Please help me how to do it and focus on how to protect the routes the amplify part I will take care of

unique vortexBOT
#

Hi @torn oxide. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

To protect your routes in Next.js using middleware, you can extend your middleware to check the authentication status of the user. Based on your description, you want to allow access to the / route for unauthenticated users and allow access to any route for authenticated users.

Here's how you can modify your middleware to achieve this:

  1. Import necessary modules: Ensure you import the necessary modules from aws-amplify and next/server.
  2. Check authentication status: Use the getCurrentUser method to determine if the user is authenticated.
  3. Redirect unauthenticated users: If the user is not authenticated, redirect them to the / route.

Here is an example of how you can implement this:

import { getCurrentUser } from 'aws-amplify/auth';
import { NextResponse } from 'next/server';

export async function middleware(req) {
  try {
    const user = await getCurrentUser();

    // If the user is authenticated, allow access to any route
    if (user) {
      return NextResponse.next();
    }
  } catch (error) {
    // If the user is not authenticated, allow access only to the '/' route
    if (req.nextUrl.pathname !== '/') {
      return NextResponse.redirect(new URL('/', req.url));
    }
  }

  return NextResponse.next();
}

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

Explanation:

  • Importing Modules: The getCurrentUser method from aws-amplify/auth is used to check the user's authentication status. The NextResponse from next/server is used to handle responses.
  • Middleware Function: The middleware function checks if the user is authenticated. If the user is authenticated, it allows access to any route by calling NextResponse.next().
  • Redirecting Unauthenticated Users: If the user is not authenticated and tries to access any route other than /, they are redirected to the / route.
  • Configuring Matcher: The matcher configuration ensures that the middleware is applied to all routes except for API routes, static files, and other specified paths.

This setup ensures that only authenticated users can access protected routes, while unauthenticated users are redirected to the / route.

For more information on protecting routes with middleware, you can refer to the Next.js documentation (https://nextjs.org/docs/app/building-your-application/authentication#optimistic-checks-with-middleware-optional).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: