Categories
Blog Javascript Learning

Solution: TypeError: Failed to construct ‘URL’: Invalid URL

Hello,

If you are facing error :


Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL
Failed to construct ‘URL’ : Invalid URL in your nextjs app

And you already have following loader ‘imgix’ settings in your next.config.js file

images: {
    // loader and path setting for android build to load nextjsimage and also on web on certain scenarios!
    loader: 'imgix',
    path: '/', // Remove the path prefix for production images
    domains: [
      'xxx.com',
      '*.xxx.com',
      'aaa.xxx.com',
      'via.placeholder.com',
    ],
}

To fix this the solution provided here worked out well!

Code snippet solution: source page stackoverflow

const loaderProp =({ src }) => {
    return src;
}

<Image
      src={currentImage.imageurl}
      alt={currentImage.imageurl} 
      layout="fill"
      className={styles.imageSize} 
      loader={loaderProp}
/>

we just need to add loader prop to the Image tag of next.js component and passdown the callback function which resolves the error above, voila!

Hope this also help you if you are facing this solution in your next.js application.

happy learning!

Categories
Javascript Learning Tech

Function getStaticPaths, How to create paths in getStaticProps function If you have no access to create paths in getStaticPaths, NEXTJS

Hello,

Hope this is very interesting question of scenario you might be facing to solve with next js and

  • when you don’t want to use “function getServerSideProps” to pass dynamic (data as) props to the page components
  • when you don’t want too make a extra API calls to generate the paths for products or whatever list of thing you are creating in “function getStaticPaths”

Here is the quick things we need to work out to work this out of box for specially the scenario were are showing product detail view page which is of route like in Nextjs as “page/product/[id].js

First in function getStaticPaths() we just need to do this and pass fallback as “true” as we our dynamic path is not pre-rendered!

export async function getStaticPaths() {
    // Empty array since paths will be dynamically created in getStaticProps
    return {
        paths: [],
        fallback: true, // Set to true if there are dynamic paths that are not pre-rendered !! 
    };
};

Next, we need to edit our “getStaticProps” function and then voila;


export async function getStaticProps({ params }) {
    const product = await getProduct(params && params.id);
    if (!product) {
        return {
            redirect: {
                destination: '/',
                permanent: false,
            },
        }
    }

    return {
        props: {
            product,
            error: resp.error ? true : false
        }
    };
}

Boom you are done, and just use those props in your page component like



return (<PhotoProvider
        key={'photoprovider-key-' + product?.id}
        speed={() => 600}
        easing={(type) => (type === 2 ? '' : 'cubic-bezier(.25, 1, .30, 1)')}>

/*...other codes*/
</PhotoProvider>

you will find you page up and working, fine!

Hope this simple steps helps to solve our complex situations arises in the development work of software building on planet earth!

I would also like to the above situation, why we can’t just do the same thing simply with getServerSideProps in single function, I am facing the issue to build using next build && next export for android package, as dynamics cannot be rendered as html files due to getServerSideProps sitting in between, and also as per the Next JS docs we can’t do anything what I have found of my learnings.

Happy Learning! Thanks for reading.

Keep coding & Develop Wonderful.

To Follow help out to know: uidevwork

Categories
Javascript Learning Tech

How to fix nextjs appending http://localhost:3000/_next/image? to the image srcset how to remove for production build for images?

Hello,

Welcome to the question and for the search, facing this issue? lets quickly see how we can fix this, with and in next.config.js file.

In Next.js, when using the next/image component, the src attribute is automatically transformed to a URL that goes through the Next.js image optimization pipeline. During development, this URL may include http://localhost:3000/_next/image? to indicate the local development server.

However, for production images, you can configure Next.js to remove the http://localhost:3000/_next/image? prefix. Here’s how you can achieve that:

Create a custom loader for Next.js images:

  • Open next.config.js and add the following code:
    • module.exports = {
    • images: {
      • loader: 'imgix',
      • path: '', // Remove the path prefix for production images
    • }, };
  • This configuration sets the loader option to use the imgix loader, which removes the http://localhost:3000/_next/image? prefix. The path option is set to an empty string, this will leave the prefix for image urls and left blank

Now you can easily build your project and test to images are loading fine with absolute url path if applied so.

Hope this help to solve the issue.

Happy Learning!

Categories
Learning Learning Tech

How to sync generated next.js out folder build to android/android studio in capacitor?

Hello, Welcome to the feel and question.

Here is a quick way do it out!

Build the Next.js project: Run the build command for your Next.js project, which typically generates a production-ready build in the “out”/ “build” folder.

npx next build && npx next export

Locate the build output: Once the build process is finished, locate the generated “out” folder in your Next.js project directory.

Copy the build output: Copy the entire contents of the “out” folder, including any subfolders and files.

Paste the build output in the Android project: Navigate to the root directory of your Android project in Capacitor. The default location is usually the “android” folder within your Capacitor project.

Paste the build output: Paste the contents of the “out” folder into the appropriate location in your Android project. By default, you can paste it into the “app/src/main/assets/public” directory of your Android project.

Sync the Android project: After pasting the build output, trigger a sync operation in Android Studio to ensure the changes are recognized. This can be done by clicking on the “Sync Project with Gradle Files” button or by selecting “File” -> “Sync Project with Gradle Files” in the Android Studio menu.

Build and run the Android project: Once the sync operation is complete, you can build and run your Android project to deploy the updated Next.js web application within your Capacitor app.

Voila you are done!.

Hope this question and learning helps.

Happy Learning!

Categories
Javascript Learning Tech

What to do when you get nextjs error (Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’) on vercel/nextjs deployment?

Hello,

If you too facing this error : Module not found: Error: Can’t resolve ‘private-next-pages/’ in ‘/vercel/path0’

while deploying your NextJs project over Vercel platform, please follow what solution and mistake I was doing.

Error Screenshot of error occurring from the NextJs Project deployment on vercel platform.

As, I tried to debug this error by right away check the the next in the log highlighted (in screenshot above) recommending to following alias rule to be set if you have touched you next.config.js file with any webpack settings.

In my case I did have to touched the next.config.js file and so I have add the same lines of code recommend in the follow link of Next.js doc

https://nextjs.org/docs/messages/invalid-resolve-alias

But for me still I didn’t found the right solution, because was in the naming of folder under nextjs project.

Basically, I was loading the static content into the dynamic route in Nextjs (Like example reference here).

What I have missed was the name of the folder under pages directory I have created named as “learn” it should be similar to name “posts” as created one at root level of the project to hold the “.md” or “.html” file content to pass down to dynamic route page which will be under /pages/posts/[id].js

Sharing here screenshot of the directory where the naming was a mistake

Here highlighted “learn” folder should be same as “posts” below

After renaming the folder name “learn” to “posts” the error went off and found my deployment working successfully.

Hope this small mistake tip help you to solve this problem.

If you have found any mistake in the post. Please don’t hesitate to hit me on my email jat@doableyo.com to rectify.

Enjoyed reading this? How about sharing with your friends or in groups, this would help!

Thanks, Happy Learning!

Categories
Javascript Learning Tech

What to do when you get Error: sgmail send error Bad Request (400) The attachment content must be base64 encoded. attachments.0.content for nodejs or in next js application?

Okay well, this error occurred when you try to send the generated buffer data as an attachment using @sendgrid/mail service.

To tackle issue, will simply paste the previous line of code and the fix line of code so data was then send as base64 content as required with the @sendgrid/mail service

  res.send(response); //previous line of response from nextjs api

after adding the fix over same above line using Buffer

  res.send(Buffer.from(response).toString('base64')); // to base64 string as an output resolve the above issue

If anyone wants to look for the entire piece of file code, here you go:

// import the necessary node libraries
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer');
import { createEmailTemplate } from "../../api/functions/index";
// var Buffer = require('buffer/').Buffer  // note: the trailing slash is important!

export default async (req, res) => {

    // console.log({ m: req.method.toLowerCase(), body: Object.keys(req.body).length });

    if (req.method.toLowerCase() !== 'post' ||
        (!Object.keys(req.body).length ||
            process.env.YOUR_EXTERNAL_API_SECRET !== req.body.your_api_secret)) {
        res.status(403).send("Access denied");
        return;
    }

    const { generateType, store } = req.body; // && JSON.parse(JSON.streq.body);
    const templatePayload = {
        ...req.body,
        assetsBaseURL: process.env.NEXT_PUBLIC_ASSETS_BASE_URL,
        siteName: process.env.SITE_NAME,
        logoPath: store?.logo,
    };
    // console.log({ templatePayload });
    try {

        // compile the file with handlebars and inject the customerName variable
        const html = createEmailTemplate("my-invoice", templatePayload);

        // simulate a chrome browser with puppeteer and navigate to a new page
        const browser = await puppeteer.launch({
            args: chromium.args,
            // defaultViewport: chromium.defaultViewport,
            // defaultViewport: generateType && generateType === 'pdf' ? chromium.defaultViewport : { width: 640, height: 1200 }, //chromium.defaultViewport,
            executablePath: await chromium.executablePath,
            headless: generateType && generateType === 'pdf' ? true : chromium.headless,
            ignoreHTTPSErrors: true,
        });

        const page = await browser.newPage();
        await page.setViewport({
            width: 640,
            height: page.viewport().height, // + 400,
            deviceScaleFactor: 1,
        });

        // set our compiled html template as the pages content
        // then waitUntil the network is idle to make sure the content has been loaded
        await page.setContent(html, { waitUntil: 'networkidle0' });

        // convert the page to pdf with the .pdf() method
        let response;
        if (generateType && generateType === 'pdf') {
            const pdf = await page.pdf({ format: 'A4' });
            response = pdf;
        } else {
            const screenshot = await page.screenshot({ fullPage: true });
            response = screenshot;
        }
        await browser.close();

        // // send the result to the client
        res.statusCode = 200;
        res.send(Buffer.from(response).toString('base64'));

        // CODE BELOW WRITE RESPONSE AS HTML AND IMAGE IS DISPLAYED, TESTTED 
        // res.writeHead(200, { 'Content-Type': 'text/html' });
        // res.write('<html><body><img src="data:image/jpeg;base64,')
        // res.write(Buffer.from(response).toString('base64'));
        // res.end('"/></body></html>');

    } catch (err) {
        console.log(err);
        res.status(500).json({ message: err.message });
    }
};

I hope this find useful to anyone who facing this question or challenge.

Happy learning! Enjoy!

Categories
Javascript Learning Learning Tech

How I have resolve, Module not found, Can’t resolve ‘optimism’

Hello welcome to this post.

Straight to the answer, here it goes:

Tried running first nextjs app

λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info  - Loaded env from F:\windows\developapp\code\.env
info  - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
error - ./node_modules/@apollo/client/cache/core/cache.js:1:0
Module not found: Can't resolve 'optimism'

Import trace for requested module:
./node_modules\@apollo\client\cache\index.js
./node_modules\@apollo\client\core\index.js
./node_modules\@apollo\client\index.js
./pages\_app.js

https://nextjs.org/docs/messages/module-not-found
Terminate batch job (Y/N)?
^C

Next reinstalled package



F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm i @apollo/client@latest --save

added 9 packages, changed 1 package, and audited 1119 packages in 13s

90 packages are looking for funding
  run `npm fund` for details

6 vulnerabilities (4 low, 2 high)

To address issues that do not require attention, run:
  npm audit fix

Some issues need review, and may require choosing
a different dependency.

Run `npm audit` for details.

Then run again! boom!

F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm run dev

> developfe-dev@1.0.0 dev
> next

ready – started server on 0.0.0.0:3000, url: http://localhost:3000
info – Loaded env from F:\windows\developapp\code\.env
info – Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
event – compiled successfully

So, here is the simple answer to the question.

Thanks for reading and Happy Learning!