localStorage is not defined (Angular Universal)

These steps resolved my issue:

Step 1: Run this command:

npm i localstorage-polyfill --save

Step 2: Add these two lines in server.ts file:

import 'localstorage-polyfill'

global['localStorage'] = localStorage;

Once you are done, run build command (eg: npm run build:serverless)

All set now. Start the server again and you can see the issue is resolved.

Note: Use localStorage not window.localStorage, eg: localStorage.setItem(keyname, value)

Leave a Comment