Tyrao
Tyrao

Reputation: 81

NextJS How to create dynamic backend routes

Is there away for me to create dynamic backend routes? I am creating and image host. I am wanting the user to be able to get their image saved on the server under a domain like this http://localhost/<random_id> and example of the link would be http://localhost/a3Fafght5, I have looked around online and I could not find anything about creating dynamic backend routes and then when I did find one thing it said I needed to use getStaticPaths to declare all the possible ids. I dont know what the id is going to be when I build the project, I need to be able to query the database with it and check if it exists and do things from there.

Upvotes: 0

Views: 464

Answers (1)

Mario Nikolaus
Mario Nikolaus

Reputation: 2406

You can use dynamic page routing if you have file like pages/[imageId].js and then simply put getServerSideProps in your file which can call your database and determine if this is valid ID or not. For valid ID your would return image, for not valid simply 404.

If you don't want to have server-side rendering, but static one instead. You could have the same file as above and have getStaticPaths function which would query the database and return array of all possible IDs. This however could be issue if you have a lot of images, then the server-side solution would be easiest.

Upvotes: 0

Related Questions