Serhii
Serhii

Reputation: 59

How to make slug image url (react, nextjs, next/image)

Can I change image url to slug url? I work with nextjs and use next/image Now a url of my image looks like"

http://localhost:3000/_next/image?url=http%3A%2F%2F127.0.0.1%3A8000%2Fmedia%2Fuimages%2F0481%2F2408696.s.jpg&w=1920&q=75

Can I change it to:

http://localhost:3000/uimages/kreplenie-dvertci-shpil_ka-tverdotoplivnogo-kotla-2408696s.jpg

or

http://127.0.0.1:8000/uimages/kreplenie-dvertci-shpil_ka-tverdotoplivnogo-kotla-2408696s.jpg

(I am also confused a bit with http://localhost:3000/ and http://127.0.0.1:8000/ what I should use at the beginning of the URL)?

P.S. I have slug for image in may data base like this: "slug_url": "https://mydomain.ua/uimages/kreplenie-dvertci-shpil_ka-tverdotoplivnogo-kotla-2408696s.jpg"

I have some ideas. For example:

  1. Use loader https://nextjs.org/docs/api-reference/next/image#loader
  2. Or use redirect and rewrites in middleware.js But I don't uderstand how to implement it if those ones are appropriate

Upvotes: 1

Views: 689

Answers (1)

Serhii
Serhii

Reputation: 59

To have regular URL of images I added in config file this:

unoptimized: true,

link to nextjs documentation

then I made rewrite in middleware file

  if (/-\d{1,}b.jpg/.test(request.nextUrl.pathname)) {
    const imageId = request.nextUrl.pathname
      .match(/-\d{1,}b.jpg/)[0]
      .slice(1, -5);
    const imageFolder = getImageFolder(imageId);
    return NextResponse.rewrite(
      new URL(
        `http://127.0.0.1:8000/media/uimages/${imageFolder}/${imageId}.b.jpg`,
        request.url
      )
    );
  }

In my Image component I used slug for image URL:

          src={
            MainImageObject.slug_url.slice(0, 6) === "https:"
              ? `${MainImageObject.slug_url.slice(24, -5)}s.jpg`
              : `${MainImageObject.slug_url.slice(18, -5)}s.jpg`
          }

Upvotes: 0

Related Questions