Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next JS dynamic import for named export

I am learning next js. I want to call a function getItem of https://www.npmjs.com/package/encrypt-storage

Using below code, but I am getting TypeError: EncryptStorage.getItem is not a function

import dynamic from 'next/dynamic';
const EncryptStorage = dynamic(() => import('encrypt-storage').then((mod) => mod.EncryptStorage(process.env.NEXT_PUBLIC_SKK)), { ssr: false });
console.log(EncryptStorage.getItem('aa'));

please help me to sort it out.

like image 521
Haren Sarma Avatar asked Jun 03 '26 08:06

Haren Sarma


1 Answers

tl;dr: You need to use await import(...) instead of dynamic(() => import(...)) as the latter is only for components.

The longer version:

This was confusing to me as well as the docs don't outright state that you can't import modules with dynamic(...), only that it should be used to import components:

React components can also be imported using dynamic imports, but in this case we use it in conjunction with next/dynamic to make sure it works just like any other React Component.

And indeed, looking at this comment from a maintainer you can't use dynamic(...) to import modules, only components.

Given this, here's a possible solution:

Also, note that .getItem(...) is a method that needs to be called on an instance of EncryptStorage.

    // Needs to be ran in an `async` context or environment that supports top-level `await`s
    const EncryptStorage = (await import("encrypt-storage")).default;
    const encryptStorage = EncryptStorage(process.env.NEXT_PUBLIC_SKK);
    console.log(encryptStorage.getItem("aa"));

And, here's a sandbox with a full working example.

like image 171
Sam Gomena Avatar answered Jun 05 '26 21:06

Sam Gomena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!