Next.js Discord

Discord Forum

How to make a 301 redirection in server side ?

Answered
Upland Sandpiper posted this in #help-forum
Open in Discord
Upland SandpiperOP
Hello there !

Do you know how to make a 301 redirection in a server page ?

I know how to do it in client side with redirect/push but in server side ?

I need to redirect in the case of a slug has changed so dynamically not in hard in next.config.js.

Thanks !
Answered by Upland Sandpiper
catSlug still contains the catId
View full answer

48 Replies

Upland SandpiperOP
Upland SandpiperOP
yes but its a 301 code
308 rather
ah got it 👍
Upland SandpiperOP
🙂
good job!
Upland SandpiperOP
what do you think of this :

export default async function CatList({ params: { catSlug } }: catSlugProps) {
  // on récupère le slug de la catégorie
  // celui-ci contient un id
  // Sépare la chaîne au tiret et prend le premier élément
  const potentialId = catSlug.split("-")[0];

  // on a maintenant l'id de la catégorie de l'url
  // on doit vérifier :

  // 1) qu'il existe et qu'il s'agit bien d'un nombre
  let catId = null;

  // si potentialId est null ou undefined
  if (!potentialId) {
    notFound();
  } else {
    catId = parseInt(potentialId, 10);
    if (isNaN(catId)) {
      // si catId n'est pas un nombre
      notFound();
    }
  }

  // 2) que la catégorie existe bien
  const askedCategory = await prisma.category.findUnique({
    where: { id: catId },
  });

  if (!askedCategory) {
    notFound();
  }

  // 3) que le slug n'est pas différent de celui en base de données
  // on récupère le slug en base de données
  const slugInDatabase = askedCategory.slug;
  if (slugInDatabase !== catSlug) {
    // si le slug est différent
    // on redirige vers la bonne url
    permanentRedirect(`/modele/${slugInDatabase}`);
  }

  return (
    <>
      <p>Rendering here.</p>
    </>
  );
}
sorry comments in french 🙂
that looks good for me. If you need the slug only for SEO, you can use generateMetaData to fetch only for the meta tags. Because I think you might fetch again at "/modele/${slugInDatabase}" right?
Upland SandpiperOP
yes
but now it's an infinite loop lol, let me take a look
haha yea xD
Upland SandpiperOP
permanentRedirect(/modele/${catId}-${slugInDatabase});
what about only one page?
Upland SandpiperOP
how ?
like push the user directly to the modele/..
Upland SandpiperOP
that's what I did ?
We done:
push the user to one page, fetch the product -> redirect -> fetch the product on other page
I mean:
push the user to the product page, fetch the product
Upland SandpiperOP
ok I'm lost... lol

just to be clear, let me explain the code
this page is supposed to load subcategories thanks to the slug from the params

- the slug contains the catId, so we extracted it
- then we checked if the catId exists in the database
- then we compare the slug params with the slug in the database : if it's not the same, we redirect to the right slug :

example :

12-apple-macbook => 12-apple-macbook-air
yea
Upland SandpiperOP
but now I'm struggling with an infinite loop lol
yes, create only one page is the key, that I would use to break the loop
Upland SandpiperOP
I don't understand, for me , I hav eonly one page
ok, for me you have 2 page.
Page 1 (CatList): this one: https://nextjs-forum.com/post/1179504824627245117#message-1179506347830681600
Page 2: "/modele/someslug"
So if we can compare both, your will be able to break it
Upland SandpiperOP
- page 1 is : /app/modele/[catSlug]/page.tsx

-page 2 is the same page as page 1 : /app/modele/[catSlug]/page.tsx

lol
ah oh, then I misunderstood that
why do we redirect? 🤔
SEO can be done in meta tags. So, we don't redirect because of SEO. Why do we redirect?
Upland SandpiperOP
we redirect because of update of the slug
to avoid duplicate content
to avoid 2 urls of the same page
12-apple-macbook is the same page as 12-apple-macbook-air
we d'ont want to have 2 results in Google pointing to the same content
are you creating a sitemap.xml for google?
Upland SandpiperOP
not now maybe later of course
with the sitemap you can remove duplicates. So while generating the xml just fetch the one. There won't be any loop
but that's maybe not the best solution.
Upland SandpiperOP
oh I found
Upland SandpiperOP
catSlug still contains the catId
Answer
Upland SandpiperOP
I have to remove the catId before comparing it to the slug in database
that's why always : slugInDatabase == catSlug
infinite loop
permanentRedirect(/modele/${catId}-${slugInDatabase}); is always launched
great to hear that 👍
Upland SandpiperOP
thanks for your time