I am getting this error when I am doing ng serve
ERROR ReferenceError: localStorage is not defined
at _ShoppingCartService.eval (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:38:7)
at Generator.next (<anonymous>)
at eval (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:94:61)
at ZoneAwarePromise (/Users/sunilsarode/SHOP/oshop/node_modules/zone.js/fesm2015/zone-node.js:1353:21)
at Module.__async (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:78:10)
at _ShoppingCartService.getCartOrCreateCartId (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:35:38)
at _ShoppingCartService.eval (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:24:29)
at Generator.next (<anonymous>)
at eval (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:94:61)
at ZoneAwarePromise (/Users/sunilsarode/SHOP/oshop/node_modules/zone.js/fesm2015/zone-node.js:1353:21)
ERROR ReferenceError: localStorage is not defined
at _ShoppingCartService.eval (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:38:7)
at Generator.next (<anonymous>)
at eval (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:94:61)
at ZoneAwarePromise (/Users/sunilsarode/SHOP/oshop/node_modules/zone.js/fesm2015/zone-node.js:1353:21)
at Module.__async (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:78:10)
at _ShoppingCartService.getCartOrCreateCartId (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:35:38)
at _ShoppingCartService.eval (/Users/sunilsarode/SHOP/oshop/src/app/services/shopping-cart.service.ts:24:29)
at Generator.next (<anonymous>)
at eval (/Users/sunilsarode/SHOP/oshop/.angular/vite-root/oshop/chunk-KS6ILM5U.mjs:94:61)
at ZoneAwarePromise (/Users/sunilsarode/SHOP/oshop/node_modules/zone.js/fesm2015/zone-node.js:1353:21)
I tried following the solution and the error is gone, but now I am doing ng build, which runs indefinitely.
private async getCartOrCreateCartId(): Promise<string> {
let cartId;
if (typeof window !== 'undefined') {
cartId = localStorage?.getItem('cartId');
}
if (!cartId) {
let result = await this.create();
if (result.key) {
if (typeof window !== 'undefined') {
localStorage?.setItem('cartId', result.key);
}
return result.key;
}
return '';
} else {
return cartId;
}
}
private create() {
return this.db.list('/shopping-carts').push({
dateCreated: new Date().getTime(),
});
}
I also read this answer localStorage is not defined (Angular Universal)
I do not have any local-storage.ts file, also I am working on the angular standalone component and hence I do not have any app.module.ts file.
angular.json
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"oshop": {
"projectType": "application",
"schematics": {},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/oshop",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.css"
],
"scripts": [],
"server": "src/main.server.ts",
"prerender": true,
"ssr": {
"entry": "server.ts"
}
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "oshop:build:production"
},
"development": {
"buildTarget": "oshop:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "oshop:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.css"
],
"scripts": []
}
},
"deploy": {
"builder": "@angular/fire:deploy",
"options": {
"version": 2
},
"configurations": {
"production": {
"buildTarget": "oshop:build:production",
"serveTarget": "oshop:serve:production"
},
"development": {
"buildTarget": "oshop:build:development",
"serveTarget": "oshop:serve:development"
}
},
"defaultConfiguration": "production"
}
}
}
}
}
server.ts
import { APP_BASE_HREF } from '@angular/common';
import { CommonEngine } from '@angular/ssr';
import express from 'express';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
import bootstrap from './src/main.server';
// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
const server = express();
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
const browserDistFolder = resolve(serverDistFolder, '../browser');
const indexHtml = join(serverDistFolder, 'index.server.html');
const commonEngine = new CommonEngine();
server.set('view engine', 'html');
server.set('views', browserDistFolder);
// Example Express Rest API endpoints
// server.get('/api/**', (req, res) => { });
// Serve static files from /browser
server.get('*.*', express.static(browserDistFolder, {
maxAge: '1y'
}));
// All regular routes use the Angular engine
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
return server;
}
function run(): void {
const port = process.env['PORT'] || 4000;
// Start up the Node server
const server = app();
server.listen(port, () => {
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
run();
package.json
{
"name": "oshop",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"serve:ssr:oshop": "node dist/oshop/server/server.mjs"
},
"private": true,
"dependencies": {
"@angular-devkit/build-angular": "^17.0.10",
"@angular/animations": "^17.0.9",
"@angular/cdk": "^17.0.5",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/fire": "^17.0.1",
"@angular/forms": "^17.0.0",
"@angular/material": "^17.0.5",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/platform-server": "^17.0.0",
"@angular/router": "^17.0.0",
"@angular/ssr": "^17.0.10",
"express": "^4.18.2",
"firebase": "^10.7.1",
"firebase-tools": "^13.0.3",
"g": "^2.0.1",
"localstorage-polyfill": "^1.0.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
},
"devDependencies": {
"@angular/cli": "^17.1.0",
"@angular/compiler-cli": "^17.0.0",
"@types/express": "^4.17.17",
"@types/jasmine": "~5.1.0",
"@types/node": "^18.18.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
}
}
Can somebody explain to me what is the issue here and how to resolve it? Thanks.