CodeBucks logo
WebNews
Cookie

How to Use Next.Js Server Side Cookie || Next.Js

How to Use Next.Js Server Side Cookie || Next.Js
0 views
2 min read
#Cookie
Table Of Content
Headings: 4 (H2: 4, H3: 0)

Hii Developer's Today i tech You how to use Next.Js Server Side Cookie.
So let's talk About -

Cookie is one type of feature it's using Developer for security ,authenticate,session help to secure any website for anything authentication like login admin login role base login .etc basically use for secure the website if cokkies used the website

server side cookie are create,read or modified on the server. like any browser,java script. it's using more secure the website,Batter performance and protect the XSS Attacks

So How to use it ?#

so read the proces and apply it on your project

code
//first import this //
import { cookies } from 'next/headers'

//Create the cookie //

import { cookies } from 'next/headers'
import { NextResponse } from 'next/server'

export async function POST() {
  cookies().set('token', 'abc123', {
    httpOnly: true,
    secure: true,
    path: '/',
    maxAge: 60 * 60 * 24 // 1 day
  })

  return NextResponse.json({ success: true })
}

//read the cokkie//

import { cookies } from 'next/headers'

export default function Page() {
  const cookieStore = cookies()
  const userToken = cookieStore.get('token')

  return (
    <div>
      <h1>Server Side Cookie</h1>
      <p>{userToken?.value || 'No token found'}</p>
    </div>
  )
}


If you using Middleware to Protect Admin,or User Dasboard page using cookie so help this code

code
//Middleware//

import { NextResponse } from 'next/server'
import { cookies } from 'next/headers'

export function middleware(req) {
  const token = cookies().get('token')

  if (!token) {
    return NextResponse.redirect(new URL('/login', req.url))
  }
}

export const config = {
  matcher: ['/admin/:path*']
}

Some Tips -#

  1. Always use httpOnly
  2. Use Middleware for route Protection