Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
Next.js dynamic routes with Firestore collection

I'm looking for a way to have a dynamic route that displays for every document in a Firestore collection using Server-side Rendering.

For example, a document called foo would exist at test.com/foo under the [doc] page component. Any time a document is added, it should be able to be accessed through its respective URL.

I've tried this method but I haven't been able to get it to work. I've also tried implementing getServerSideProps but have not had much success, any pointers would be appreciated.

Code from the method above as follows:

under pages/api/[doc].js

export default (req, res) => {
  db.collection("docs")
    .doc(req.query.name)
    .get()
    .then((doc) => {
      res.json(doc.data());
    })
    .catch((error) => {
      res.json({ error });
    });
};

under pages/[shoal].jsx

import { useRouter } from "next/router";
import useSWR from "swr";

const fetcher = async (...args) => {
  const res = await fetch(...args);

  return res.json();
};

function Doc() {
  const router = useRouter();
  const { name } = router.query;
  const { data } = useSWR(`/api/${name}`, fetcher);

  if (!data) {
    return "Loading...";
  }

  return (
    <div>
      <p>Title: {data.title}</p>
    </div>
  );
}

export default Doc;

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can try using getServerSideProps:

export const getServerSideProps = async (ctx) => {
  const doc = await db.collection("docs").doc(ctx.query.id).get()
  const data = doc.data()
  if (!data) return { notFound: true };
  return { props: { data } };
};

function Doc({data}) {
  const router = useRouter();
  const { name } = router.query;

  if (!data) {
    return "Loading...";
  }

  return (
    <div>
      <p>Title: {data.title}</p>
    </div>
  );
}

export default Doc;
about 4 years ago · Juan Pablo Isaza Report

0

Simple solution.

const { data } = useSWR(api ? '/api/${name}' : null, fetcher);

Conditionally fetch the data if your variable is defined, if not, don't pass a URL string, better yet; you can conditionally consider the fetcher for usage also.

const { data } = useSWR(name ? '/api/${name}' : null, name ? fetcher : null);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!