Next js cookie
Hey readers, in this article we will be learning about what is cookie in Next js and why is it used for building web applications. If you are new to Next js then do checkout the Next js course on Codedamn or article related to Next js on Codedamn.
A cookie is a method of saving a user’s information in a cache. Data from the cache can be stored in the cookie in a variety of ways. A cookie is used to store the user data temporarily. Apart from this, it is also used to store the login session of the user so that the user doesn’t have to log in again. But it is temporary because it logout after a certain interval.
By using Local Storage
There are a number of ways to persist the user’s data in any framework like React or any Single Page Application. Local Storage is commonly used for storing the cookie and user data and then loading them when required. While this approach is easy and effective but it is vulnerable to attacks which lead to security issues in the application.
Using cookies is the safest option but it’s not reliable. Nowadays, a mixture of both, the cookie and JWT token which is JSON Web Token is used with expiry in order to persist user’s session and are forced to re-login whenever the session expires in the cache.
In order to use cookies in Next js, we need to install two packages, cookie, and react-cookie. react-cookie is useful because it allows us to set cookies from the client-side, whereas the cookie package allows us to access cookies from the server-side. In order to install it in the application, type the command: npm install react-cookie.
Cookie setup in the application
import { useCookies } from "react-cookie"
const Login = () => {
const [cookie, setCookie] = useCookies(["user"])
const handleSignIn = async () => {
try {
const response = await yourLoginFunction(username) //handle API call to sign in here.
const data = response.data
setCookie("user", JSON.stringify(data), {
path: "/",
maxAge: 3600, // Expires after 1hr
sameSite: true,
})
} catch (err) {
console.log(err)
}
}
return (
<>
<label htmlFor="username">
<input type="text" placeholder="enter username" />
</label>
</>
)
}
export default Login
When both the packages are installed, the setup of the cookie is done. It is usually done to store a user login session. To set a cookie for user login, write the code given below.
In this example, setCookie hook is called from react-cookies and is then set to the default name which is a user in this case. When the request for login is made for a user by calling a function, it takes the response from the API, stringifies the data, and stores the data in the cookie. Apart from this, the expiry time of the cookie is set so that the user has to log in again.
To access cookie within an API route in Next js, getInitialProps, and getServerSideProps is used. The getInitialProps can be executed on both the server and client-side. For checking client-side or server-side, the below code can be used within an application.
Homepage.getInitialProps = ({ req }) => {
const isServer = !!req
const isBrowser = !req
}
For accessing client-side cookies in Next js, the cookie-cutter module is used. It has no external dependencies and is efficient.
import cookieCutter from 'cookie-cutter'
// Get a cookie
cookieCutter.get('myCookieName')
// Set a cookie
cookieCutter.set('myCookieName', 'some-value')
// Delete a cookie
cookieCutter.set('myCookieName', '', { expires: new Date(0) })
For accessing Server-side cookies in Next js, the cookies module is used on the request/response object.
import Cookies from 'cookies'
Homepage.getInitialProps = ({ req, res }) => {
const cookies = new Cookies(req, res)// Create a cookies instance
cookies.get('myCookieName') // Get a cookie
cookies.set('myCookieName', 'some-value', { // Set a cookie
httpOnly: true // true by default
})
cookies.set('myCookieName') // Delete a cookie
}
Conclusion
This was about cookies in Next js it is crucial to know the concepts of cookies for building better applications, if you want to learn more about Next js, do check out the article and course on Codedamn of Next js. Hope you liked this, if you have any queries or suggestions do let us know in the comments.
If you are interested in learning React, do check out courses on codedamn with an inbuilt environmental playground to learn and practice code. If you’re interested in learning React, codedamn offers courses with a built-in environment playground where you can learn and practice code. Join the codedamn community, read other programming and development articles on the site, and sign up for our newsletter to be informed about new programs and upgrades.
Sharing is caring
Did you like what Agam singh, Aman Ahmed Siddiqui, Aman Chopra, Aman, Amol Shelke, Anas Khan, Anirudh Panda, Ankur Balwada, Anshul Soni, Arif Shaikh, wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: