Arne
Arne

Reputation: 6240

Use Strapi to manage a list of 301 redirects on the frontend

I have a Strapi (v4) backend and a Nuxt (v2) frontend, all the content is fetched using REST and GraphQL. Each environment runs on a different server and domain (provider is Digital Ocean)

My client wants to use Strapi to manage a list of 301 redirects (including regex), that is applied on the frontend.

So a visitor can be redirected from www.site.com/old-url to www.site.com/new-url while Strapi runs on backend.site.com

I'm not sure how to approach this. I'm currently using middleware in Nuxt to make redirects, but could I use ajax to fetch a list of redirects from Strapi? This would slow down every request. Could I make some sort of script that fetches the redirects from Strapi and saves it to a JSON file that the middleware could use? That might work, but is seems not very elegant.

Is there a better solution that I'm overlooking?

Upvotes: 1

Views: 1147

Answers (1)

atazmin
atazmin

Reputation: 5707

This helped me with Strapi CMS v5 and NextJs v13, I am guessing something similar can be made with Nuxt, this works at build time, from my understanding there is way to make this work at runtime

enter image description here (https://www.npmjs.com/package/strapi-plugin-redirects)

enter image description here

NextJs create redirects.js

const getRedirects = async () => {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_STRAPI_API}/redirects`);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();

    return data.redirects.map(({ from, to, type }) => ({
      source: from.startsWith('/') ? from : `/${from}`,
      destination: to,
      permanent: type === 'moved_permanently_301',
    }));
  } catch (error) {
    console.error('Failed to fetch redirects:', error);
    return [];
  }
};

module.exports = getRedirects;

add

const getRedirects = require('./lib/redirects'); 
...
  async redirects() {
    return await getRedirects();
  }

to next.config.js

/** @type {import('next').NextConfig} */
const getRedirects = require('./lib/redirects'); 

const nextConfig = {
  reactStrictMode: true, //React StrictMode renders components twice on dev server
  swcMinify: true,
  optimizeFonts: true,
  compress: true,
  images: {
    remotePatterns: [
      {
        protocol: "https",
        hostname: "res.cloudinary.com",
      },
    ],
    minimumCacheTTL: 1500000,
  },
  experimental: {
    fontLoaders: [{ loader: "@next/font/google" }],
  }, 
  async redirects() {
    return await getRedirects();
  }
};

module.exports = nextConfig;

Upvotes: 0

Related Questions