0
votes

in next.js, we can use

getStaticProps (Static Generation): Fetch data at build time.

getStaticPaths (Static Generation): Specify dynamic routes to pre-render based >on data.

getServerSideProps (Server-side Rendering): Fetch data on each request.

to run serverside code , but in order to do that , i need to import serverside module in that script ,for example, i want to import an authentication module to check user is genuine or not in getserversideprops . (or database schemas, for example, mongoose)

Since i cannot import in an function , i have to import on the top of the file which means that anyone can see that import and see how i authenticate user .....

example:

import a from 'auth"  

getserversideprops(){

if(a(req) ==true) ... 

}

1

1 Answers

0
votes

getServerSideProps will run only on the server and this code will not be bundled with the client or the final generated page. Since you should never ever ship the server side code to the client, Next.js already handles it.

Here is an example how to authenticate on server.

import auth0 from "auth0ConfigPath"
export const getServerSideProps = ({ req, res }) => {
  const session = await auth0.getSession(req); 
  if (!session || session.user) {
    res.writeHead(302, {
      Location: "/api/v1/login",
    });
    res.end();
    return { props: {} };
  }
  return {
    props:{user:session.user}
  }
};