javascriptcookiesservernext.js13react-server-components

How to save cookie on server side in next js through middleware


following official next js docs i can get cookies on server side using middleware

import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  // Assume a "Cookie:nextjs=fast" header to be present on the incoming request
  // Getting cookies from the request using the `RequestCookies` API
  let cookie = request.cookies.get('nextjs')
  console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
  const allCookies = request.cookies.getAll()
  console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
 
  request.cookies.has('nextjs') // => true
  request.cookies.delete('nextjs')
  request.cookies.has('nextjs') // => false
 
 
}

how can I save my cookie on server side to then use cookie in server components


Solution

  • there is cookies function:

    Good to know: .set() is only available in a Server Action or Route Handler.

    this is cookies function:

    function cookies() {
        if ((0, _staticgenerationbailout.staticGenerationBailout)("cookies", {
            link: "https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering"
        })) {
            return _requestcookies.RequestCookiesAdapter.seal(new _cookies.RequestCookies(new Headers({})));
        }
        const requestStore = _requestasyncstorage.requestAsyncStorage.getStore();
        if (!requestStore) {
            throw new Error("Invariant: cookies() expects to have requestAsyncStorage, none available.");
        }
        const asyncActionStore = _actionasyncstorage.actionAsyncStorage.getStore();
        if (asyncActionStore && (asyncActionStore.isAction || asyncActionStore.isAppRoute)) {
            // We can't conditionally return different types here based on the context.
            // To avoid confusion, we always return the readonly type here.
            return requestStore.mutableCookies;
        }
        return requestStore.cookies;
    }`
    

    requestStore.cookies is RequestCookies class instance which is:

    declare class RequestCookies {
        constructor(requestHeaders: Headers);
        [Symbol.iterator](): IterableIterator<[string, RequestCookie]>;
        /**
         * The amount of cookies received from the client
         */
        get size(): number;
        get(...args: [name: string] | [RequestCookie]): RequestCookie | undefined;
        getAll(...args: [name: string] | [RequestCookie] | []): RequestCookie[];
        has(name: string): boolean;
        set(...args: [key: string, value: string] | [options: RequestCookie]): this;
        /**
         * Delete the cookies matching the passed name or names in the request.
         */
        delete(
        /** Name or names of the cookies to be deleted  */
        names: string | string[]): boolean | boolean[];
        /**
         * Delete all the cookies in the cookies in the request.
         */
        clear(): this;
        toString(): string;
    }
    
        
    

    if you want to set it on middleware,

    response.cookies.set(({
           name:"foo",
           value:"bar",
           path:"/"
    }))