skip to Main Content

I am working on a Next.js project with authentication and am putting some URLs as strings into an array called protectedRoutes, so people get redirected when they access those URLs before they sign in.

const protectedRoutes = ["/home", "/profile", etc.];

I also got some posts to display in my project where each post will have its own page.
Each post has a unique id stored in firebase and I had set up the router query already in Next.js.

Let say I have a post.id == "BjPDBvsWIsa11l6JxFOAgzR3mnG3" so its URL would be /post/BjPDBvsWIsa11l6JxFOAgzR3mnG3.

My question is, how do I store each post’s URL into the protectedRoutes array? Is there a way I can do this with Regex?

Thank you very much.

const postURL = new RegExp("/post/")
const protectedRoutes = ["/home", "/profile", postURL];

is not working.

Edit 29/3:

I also wish to avoid the following:

const postID = getPostID() // function that fetches post IDs from firebase

postID.forEach((id) => {
  protectedRoutes.push(`/post/${id}`);
});

so to avoid making a long array once the number of posts grows, which slows down the search.

Edit 30/3:

Below shows the file containing protectedRoutes and the component that handles redirection.

In my _app.js,

import PrivateRoute from "@/components/PrivateRoute";
import { AuthProvider } from "@/contexts/AuthContext";
import "@/styles/globals.css";

export default function App({ Component, pageProps }) {
  const protectedRoutes = ["/home", "/profile"];
  const publicRoutes = [
    "/",
    "/sign-in",
    "/sign-in/phone",
    "/sign-up",
    "/reset-password",
  ];

  return (
    <AuthProvider>
      <PrivateRoute
        protectedRoutes={protectedRoutes}
        publicRoutes={publicRoutes}
      >
        <Component {...pageProps} />
      </PrivateRoute>
    </AuthProvider>
  );
}

and in my PrivateRoute.jsx,

import { useEffect } from "react";
import { useRouter } from "next/router";

import { useAuth } from "@/contexts/AuthContext";
import FullPageLoader from "./FullPageLoader";

export default function PrivateRoute({
  protectedRoutes,
  publicRoutes,
  children,
}) {
  const router = useRouter();
  const { currentUser, loading } = useAuth();

  const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1;
  const pathIsPublic = publicRoutes.indexOf(router.pathname) !== -1;

  useEffect(() => {
    if (!loading && !currentUser && pathIsProtected) {
      router.push("/sign-in");
    }

    if (!loading && currentUser && pathIsPublic) {
      router.push("/home");
    }
  }, [currentUser, loading, pathIsProtected, pathIsPublic]);

  if ((loading || !currentUser) && pathIsProtected) {
    return <FullPageLoader />;
  }

  if ((loading || currentUser) && pathIsPublic) {
    return <FullPageLoader />;
  }

  return children;
}

2

Answers


  1. Test follow code,

      const url1 = '/post/dadsa'
      const url2 = '/post/sdadasdas/dadsa'
      const url3 = '/postsdadasdas/dadsa'
      const url4 = '/'
      const url5 = ''
    
      const getRealPath = (url) => url.split('/').filter(v=>v!=='')[0] ? '/' + url.split('/').filter(v=>v!=='')[0] : url
    
      console.log(getRealPath(url1))
      console.log(getRealPath(url2))
      console.log(getRealPath(url3))
      console.log(getRealPath(url4))
      console.log(getRealPath(url5))
    

    Edit your app.js,

      const protectedRoutes = ["/home", "/profile", "/post"];
    

    Edit your PrivateRoute.jsx,

    + const getRealPath = (url) => url.split('/').filter(v=>v!=='')[0] ? '/' + url.split('/').filter(v=>v!=='')[0] : url
    
    - const pathIsProtected = protectedRoutes.indexOf(router.pathname) !== -1;
    + const pathIsProtected = protectedRoutes.indexOf(getRealPath(router.pathname)) !== -1;
    
    Login or Signup to reply.
  2. 
    const protectedRoutes = ["/home", "/profile", etc.];
    
    // Create /home|/profile|etc.
    const strRegProtected = protectedRoutes.join('|').replace(///g, '\/')
    
    // Create /^(/home|/profile|etc.)/
    const regProtected = RegExp(`^(${strRegProtected})`)
    
    const isUrlProtected = regProtected.test('/home/85948')
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search