Session Cookie control in Nuxt3

Nuxt

Language :

Hi, I’m Lovefield.

All my recent projects are being transferred to Nuxt3. The new version of Nuxt is also a part of it, but it's more about using TypeScript. Since I used to manage sessions using cookies, I would like to organize various methods that I have set up to manage the same in Nuxt3.

Nuxt2 has Cookie managed with the “cookie-universal-nuxt’ module. But Nuxt3 is to support Cookies managed in composables. Composables has methods useCookie and setCookie,getCookie. Among them setCookiegetCookie is only used in server logic.

You can use useCookie method with next :

html

<template>
  <div>
    <h1>Counter: {{ counter || '-' }}</h1>
    <button @click="counter = null">reset</button>
    <button @click="counter--">-</button>
    <button @click="counter++">+</button>
  </div>
</template>

<script setup>
const counter = useCookie('counter')
counter.value = counter.value || Math.round(Math.random() * 1000)
</script>

It is so much simpler than using “cookie-universal-nuxt” module in Nuxt2.

And you can use setCookiegetCookie in server logic with next:

javascript

export default defineEventHandler(event => {
  // Read counter cookie
  let counter = getCookie(event, 'counter') || 0

  // Increase counter cookie by 1
  setCookie(event, 'counter', ++counter)

  // Send JSON response
  return { counter }
})

defineEventHandler function is supported by server side logic. You can control it with the setCookie and getCookie functions. Server side Cookie logic can be used only with setCookie and getCookie functions.

Now, we are making a Session Cookie.

html

<template></tempalte>

<script setup lang=”ts”>
async function loginAction(){
    const makeCookie = await $fetch(“/api/set-cookie”,{
        method:”post”,
        body:{key:”session key value”}
    });
}
</script>

The login page requests communication from the server API provided by Nuxt3 through the function loginAction. The request was sent to the file "~/server/api/set-cookie.post .ts" using the "post" method and passed the session key to the body, which is the value for the cookie.

javascript

export default defineEventHandler(async (event) => {
    const body = await readBody(event);

    try {
        setCookie(event, "hwitturuSessionKey", body.key, {
            path: "/",
            sameSite: true,
            httpOnly: true,
        });

        return {
            result: true,
        };
    } catch {
        return {
            result: false,
        };
    }
});

This code is the “set-cookie.post.ts” file. The server communication from the function loginAction is to be returned within the function defineEventHandler. Assign the key value passed to the body as a cookie using the 'setCookie' provided by Nuxt3.

Set the httpOnly option. Because I want the client side can't control the Cookie. And did not set "maxAge" or "expires". If you do not set "maxAge" or "expires" options Nuxt3 delete Cookie when closing the browser.

Next step is logout logic. Create ~/server/api/del-cookie.get.ts file. The following code is used to delete cookies as a get request to the server.

javascript

export default defineEventHandler(async (event) => {
    try {
        setCookie(event, "hwitturuSessionKey", "", {
            maxAge: -1,
            path: "/",
            sameSite: true,
            httpOnly: true,
        });

        return {
            result: true,
        };
    } catch {
        return {
            result: false,
        };
    }
});

Unlike useCookie, cookies cannot be deleted by declaring null for the value, so set maxAge to -1 to clear them. And dean middlerwear read Cookie and set session data.

Lovefield

Web Front-End developer

하고싶은게 많고, 나만의 서비스를 만들고 싶은 변태스러운 개발자입니다.