nookies
v2.5.2
Koleksi Pembantu Kue untuk Next.js
Mengatur dan menghancurkan cookie juga berfungsi di sisi server.
yarn add nookies
Anda dapat bermain dengan kode contoh di sini.
import nookies from 'nookies'
export default function Me ( ) {
return < div > My profile </ div >
}
export async function getServerSideProps ( ctx ) {
// Parse
const cookies = nookies . get ( ctx )
// Set
nookies . set ( ctx , 'fromGetInitialProps' , 'value' , {
maxAge : 30 * 24 * 60 * 60 ,
path : '/' ,
} )
// Destroy
// nookies.destroy(ctx, 'cookieName')
return { cookies }
} import { parseCookies , setCookie , destroyCookie } from 'nookies'
function handleClick ( ) {
// Simply omit context parameter.
// Parse
const cookies = parseCookies ( )
console . log ( { cookies } )
// Set
setCookie ( null , 'fromClient' , 'value' , {
maxAge : 30 * 24 * 60 * 60 ,
path : '/' ,
} )
// Destroy
// destroyCookie(null, 'cookieName')
}
export default function Me ( ) {
return < button onClick = { handleClick } > Set Cookie </ button >
} const express = require ( 'express' ) ;
const dev = process . env . NODE_ENV !== 'production' ;
const app = next ( { dev } ) ;
const handle = app . getRequestHandler ( ) ;
const { parseCookies , setCookie , destroyCookie } = require ( 'nookies' ) ;
app . prepare ( )
. then ( ( ) => {
const server = express ( ) ;
server . get ( '/page' , ( req , res ) => {
// Notice how the request object is passed
const parsedCookies = parseCookies ( { req } ) ;
// Notice how the response object is passed
setCookie ( { res } , 'fromServer' , 'value' , {
maxAge : 30 * 24 * 60 * 60 ,
path : '/page' ,
} ) ;
// destroyCookie({ res }, 'fromServer');
return handle ( req , res ) ;
} ) ;
) ; Untuk penggunaan sisi klien, hilangkan parameter
ctx. Anda dapat melakukannya dengan mengaturnya ke objek kosong ({}),nullatauundefined.
parseCookies(ctx, options) atau nookies.get(ctx, options)Next.js context || (Express request object)a custom resolver function (default: decodeURIComponent)setCookie(ctx, name, value, options) atau nookies.set(ctx, name, value, options)Jangan lupa untuk mengakhiri tanggapan Anda di server dengan
res.send().
(Next.js context) || (Express request object)destroyCookie(ctx, name, options) atau nookies.destroy(ctx, 'token', options)Jangan lupa untuk mengakhiri tanggapan Anda di server dengan
res.send(). Ini mungkin alasan cookie Anda tidak dihapus.
(Next.js context) || (Express response object)Mit