Now getServiceSideProps
can sometimes be useful.
I also want to mention how you would use it
with a dynamic page.
Here before, when we used getStaticProps,
we also needed getStaticPaths
to let Next.js know which instances of this page
should be pre-generated.
Now when using getServiceSideProps, that's not the case.
If I do have a [Uid].js file, Uid in square brackets,
so that I have a dynamic page for a single user
for different user IDs.
If we use getServiceSideProps we don't need
and we can't use getStaticPaths.
So here, if I have the UserIdPage
and I get some props here
and here I then simply return h1 tag where I put props,
id something like this, and we then export this.
If we do all of that,
and I then also have this async getServerSideProps function
which we export.
If we have this, then you will see
that we don't need getStaticPaths at all.
Here I just returned an object,
and now I'm interested in the concrete param value
which I'm getting here.
So we can get access to that through context.
From there we can still extract params as I mentioned,
and from params we can still get our userId
by accessing uid, since that's the identifier I picked
between square brackets.
And then in the props which we passed
to the component function,
we could have the id prop, since I'm accessing that here
and set this equal to userid-
and then let's say the userId we extracted from the URL,
just to have some dummy code here that proves
that this code actually did execute
before this component function code ran.
With that if you wanna test this,
we first of all need to make sure we get rid of [pid].js
because otherwise we have two dynamic segment pages
on the same level in our pages folder,
so Next.js wouldn't know if a value after slash
nothing should be a product ID or a user ID,
and therefore if I move to pitfall
into the products folder here.
And in index.js I update my links
to go to /products/some ID,
now we resolve the disc clash because now we know
that if it's just slash something unrecognized,
it will always target this user ID route.
And now with that, if I bring back that development server,
if we visit let's say /u1 for user one,
we see userid-u1 here so it worked.
And it did work without us adding getStaticPaths.
Why? Because this runs on the server only anyways.
So Next.js does not pre generate any pages at all,
and therefore of course, it also doesn't need to know
which pages to pre-generate
because there is no pre-generation.
So unlike in the other case with getStaticProps
where we do pre-generate pages
and where we therefore for do need to tell Next.js
for which param values pages should be pre-generated,
with getServiceSideProps that's simply not an issue
because we run that server side code
for every request anyways.
So there is no pre-generation
and therefore no need to define those dynamic paths
in advance.
I hope that makes sense.