Security, Tech & Programming
Next.js CheatSheet

Next.js CheatSheet

.htaccess file for static Next.js build

You can generate the static html version of nextjs through:

npx next build
npx next export

This will generate the static version of your site in /out folder.

You can copy that out folder to the root of your webhosting, e.g. in public_html/

Then add this .htaccess file to the same folder if required:

<IfModule mod_rewrite.c>

  RewriteEngine On
  RewriteBase /
  RewriteRule ^index.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-L
  RewriteRule . /index.html [L]

</IfModule>

Loop images dynamically and with same path and name

This code loads images dynamically from any specified folder and also keeps the path and name of the folder same.

import Image from "next/image";

const dirPath = '/assets/images/app_screens/';
const images = require.context(
  "public/assets/images/app_screens/",
  false,
  /^\.\/(?!.*\/)[^.]+\.(png|jpe?g|gif|webp)$/i
);
const imagePaths = images.keys();

export default function Output() {
  return (
    <>
      {imagePaths.map((imagePath, index) => (
        <Image key={index}
          src={`${dirPath}${imagePath.replace("./", "")}`}
          width={100}
          height={100}
        />
      ))}
    </>
  );
}

More details on this topic here: https://socalledhacker.com/nextjs-import-images-dynamically-from-directory/

Leave a Reply

Your email address will not be published. Required fields are marked *

Hire Me!