Next.js Discord

Discord Forum

How to secure .env variable in class component

Answered
Rhinelander posted this in #help-forum
Open in Discord
RhinelanderOP
I am having an security issue. I expose my NEXT_PUBLIC_STRAPI_API_TOKEN with NEXT_PUBLIC prefix. This allows me to work with this in client components.

Code on image is just simple stuff that allows me to use my pagination.

Everything works fine I am just concerned about security. I expose my important API token to the client meaning that anyone could use it.

  const [posts, setPosts] = useState<Posts | undefined>(undefined);
  const searchParams = useSearchParams();
  const currentPage = Number(searchParams.get('page')) || 1;

  useEffect(() => {
    const fetch = async () => {
      const posts = await getPosts(
        `?locale=sl-SI&pagination[pageSize]=12&pagination[page]=${currentPage}&populate=*`
      );
      setPosts(posts);
    };
    fetch();
  }, [currentPage]);
Answered by American Crow
I would split this up in a server and a client component.
Here is a minimal example

// server component e.g page.tsx
export default function Page({searchParams}) {
  // can retrieve variables safely here
  const currentPage = Number(searchParams.page) ?? 1
  const posts = await getPosts(`...`)
  return (
    <SomeClientComponent posts={posts} />
  )
}


"use client"
export default function SomeClientComponent({posts}) {
  const searchParams = useSearchParams();
  const currentPage = Number(searchParams.get('page')) || 1;
  ...

  return(    
    <button onClick={() =>
        rounter.push(`?page=${currentPage+1}`)
    }>
        Next Page
    </button>
  )
}

Coded from memory in discord so there most likely some errors, but you get the idea.
View full answer

5 Replies

American Crow
I would split this up in a server and a client component.
Here is a minimal example

// server component e.g page.tsx
export default function Page({searchParams}) {
  // can retrieve variables safely here
  const currentPage = Number(searchParams.page) ?? 1
  const posts = await getPosts(`...`)
  return (
    <SomeClientComponent posts={posts} />
  )
}


"use client"
export default function SomeClientComponent({posts}) {
  const searchParams = useSearchParams();
  const currentPage = Number(searchParams.get('page')) || 1;
  ...

  return(    
    <button onClick={() =>
        rounter.push(`?page=${currentPage+1}`)
    }>
        Next Page
    </button>
  )
}

Coded from memory in discord so there most likely some errors, but you get the idea.
Answer
RhinelanderOP
Thank you... will test it as soon as i came back home and report you back the results
RhinelanderOP
thank you! It works!