DEV Community 👩‍💻👨‍💻

Dylan Muraco
Dylan Muraco

Posted on

Server Side Rendering, Prisma + Next.js + TypeScript

I've been working on a new project recently (CodeComponents if you wanna check it out) and struggled a little bit figuring out server side rendering because typescript wants to know what is being passed to the pages so I wanted to share how to do it.


so lets say we have a helper function that just returns all posts from the database

const prisma = new PrismaClient()
async function getPosts() {
    const posts = await prisma.post.findMany()
    return posts
}
Enter fullscreen mode Exit fullscreen mode

Static Site Generation


export const getStaticProps: GetStaticProps<{
    posts: Prisma.PromiseReturnType<typeof getPosts>
}> = async () => {
    const posts = await getPosts()
    return {
        props: {
            posts
        }
    }
}

const Home: NextPage<InferGetStaticPropsType<typeof getStaticProps>> = (
  props: InferGetStaticPropsType<typeof getStaticProps>
) => {
    return (
        <div>
            ...
            {/* do whatever with posts here */}
        </div>
    )
}

export default Home;

Enter fullscreen mode Exit fullscreen mode

Server Side Rendering

Server Side rendering is pretty similar we just have to change the type of props passed to page function

export const getServerSideProps: GetServerSideProps<{
    posts: Prisma.PromiseReturnType<typeof getPosts>
}> = async () => {
    const posts = await getPosts()
    return {
        props: {
            posts
        }
    }
}

const Home: NextPage<InferGetServerSidePropsType<typeof getServerSideProps>> = (
  props: InferGetServerSidePropsType<typeof getServerSideProps>
) => {
    return (
        <div>
            ...
            {/* do whatever with posts here */}
        </div>
    )
}

export default Home;

Enter fullscreen mode Exit fullscreen mode

Hope this was helpful

Top comments (0)

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.