nextjs localstorage
- Create a new Next.js project:
npx create-next-app my-nextjs-app
cd my-nextjs-app
- Install
js-cookie
package for working with cookies:
npm install js-cookie
- Create a new component for handling local storage operations, for example,
LocalStorage.js
:
// components/LocalStorage.js
import Cookies from 'js-cookie';
export const setLocalStorageItem = (key, value) => {
localStorage.setItem(key, JSON.stringify(value));
};
export const getLocalStorageItem = (key) => {
const item = localStorage.getItem(key);
return item ? JSON.parse(item) : null;
};
export const removeLocalStorageItem = (key) => {
localStorage.removeItem(key);
};
export const setCookie = (key, value, options) => {
Cookies.set(key, value, options);
};
export const getCookie = (key) => {
return Cookies.get(key);
};
export const removeCookie = (key) => {
Cookies.remove(key);
};
- Use the
LocalStorage
functions in your Next.js pages or components:
// pages/index.js
import { useEffect } from 'react';
import { setLocalStorageItem, getLocalStorageItem } from '../components/LocalStorage';
const HomePage = () => {
useEffect(() => {
// Set an item in local storage
setLocalStorageItem('user', { name: 'John', age: 25 });
// Get an item from local storage
const user = getLocalStorageItem('user');
console.log(user); // Output: { name: 'John', age: 25 }
}, []);
return (
<div>
<h1>Next.js Local Storage Example</h1>
</div>
);
};
export default HomePage;
- Run your Next.js application:
npm run dev
Visit http://localhost:3000
in your browser to see the example in action.