Home > Software design >  Use getServerSideProps in Dynamic Routes
Use getServerSideProps in Dynamic Routes

Time:01-12

I'm trying to use getServerSideProps in my file [username].js (which uses dynamic routing). To use dynamic routing in next.js, you need to use the two functions getStaticPaths() and getStaticProps({ params }). However, you cannot use getServerSideProps with getStaticProps. This is a problem because I need to use getServerSideProps({ req, res }) to access headers containing important user info (such as req.headers['x-user-name']), and without that data I cannot properly add functionality to my application. What can I do here?

CodePudding user response:

You don't need to use getStaticPaths and getStaticProps in a dynamic route file.

You can just use getServerSideProps and use the params object to get the username inside of it.

Example usage:

export async function getServerSideProps({ params, req }) {
    let pageUserInDb = await User.findOne({ username: params.username }).populate('userRoles');
    return {
        props: {
            pageUser: pageUserInDb
        }
    }
  • Related