쿠키 플러그인
쿠키 플러그인 (Cookies Plugin)
이것은 표준화된 document.cookie의 래퍼예요. JSON 객체와 문자열을 모두 읽고 쓰며, SSR/SSG 빌드의 서버 쪽에서 요청 쿠키를 관리하고, 쿠키를 Vue ref에 바인딩해요(v2.34+): $q.cookies.useCookie('theme')는 쿠키를 읽고 쓰며, 앱 어디에서든 플러그인을 통해 변경될 때마다 업데이트돼요.
출처: 문서
본문
Cookies API
Methods (메서드)
get(name: string): string | object | any[]쿠키 가져오기 파라미터:name(string, required) 쿠키 이름 예시:'userId'반환:string | object | any[]디코딩된 쿠키 값; JSON 쿠키는 Object나 Array로 파싱돼요; 쿠키가 없으면 null을 반환해요 예시:'john12',{ theme: 'dark' }
getAll(): object모든 쿠키 가져오기 반환:object쿠키 이름(키)과 값의 객체로, get()이 반환하는 것처럼 디코딩되고 파싱돼요 예시: -{ userId: 'john12', XFrame: 'x534' }set(name: string, value: string | number | boolean | object | any[], options?: object): void쿠키 설정 파라미터:name(string, required) 쿠키 이름 예시:'userId'value(string | number | boolean | object | any[], required) 쿠키 값; Object나 Array는 JSON으로 저장되고 get()으로 다시 파싱돼요; 그 외의 값은 String으로 다시 읽혀요 예시:'john12',{ theme: 'dark' }options(object, optional) 쿠키 옵션 객체 형태:expires(number | string | Date, optional) 쿠키 만료 상세; Number로 지정하면 단위는 일(day)이에요; String으로 지정하면 원시 문자열 날짜이거나 Xd Xh Xm Xs 형식일 수 있어요(예시 참고) 예시:30'Wed, 13 Jan 2021 22:23:01 GMT''1d''15m''13d''1d 15m''1d 3h 5m 3s'
path(string, optional) 쿠키 경로 예시:'/accounts'domain(string, optional) 쿠키 도메인 예시:'.foo.com'sameSite(string, optional) SameSite 쿠키 옵션 허용값:'Lax','Strict','None'httpOnly(boolean, optional) Http Only 쿠키인가요?secure(boolean, optional) 보안 쿠키인가요? (https 전용)other(string, optional) 다른 쿠키 옵션을 위한 원시 문자열; Quasar에 아직 구현되지 않은 더 새로운 props를 위한 최후의 수단으로 사용돼요 예시:'SomeNewCookieProp'
has(name: string): boolean쿠키가 존재하는지 확인 파라미터:name(string, required) 쿠키 이름 예시:'userId'반환:boolean쿠키가 존재하는지 여부
remove(name: string, options?: object): void쿠키 제거 파라미터:name(string, required) 쿠키 이름 예시:'userId'options(object, optional) 쿠키 옵션; 쿠키는 설정할 때와 같은 path와 domain을 가진 쓰기에 의해서만 제거되고,__Secure-또는__Host-접두사가 붙은 것은 secure도 필요해요 객체 형태:path(string, optional) 쿠키 경로 예시:'/accounts'domain(string, optional) 쿠키 도메인 예시:'.foo.com'sameSite(string, optional) SameSite 쿠키 옵션 허용값:'Lax','Strict','None'httpOnly(boolean, optional) Http Only 쿠키인가요?secure(boolean, optional) 보안 쿠키인가요? (https 전용)other(string, optional) 다른 쿠키 옵션을 위한 원시 문자열; Quasar에 아직 구현되지 않은 더 새로운 props를 위한 최후의 수단으로 사용돼요 예시:'SomeNewCookieProp'
useCookie(name: string, options?: object): object쿠키에 바인딩된 Vue ref를 가져와요: 쿠키 값을 읽고(없으면 기본값 또는 null), 할당하면 값을 저장하며(null은 쿠키를 제거하거나 기본값으로 재설정) Object나 Array 값의 중첩 변경도 저장돼요. set()/remove()를 통한 변경, 같은 쿠키의 다른 ref를 통한 변경, 그리고 브라우저에 Cookie Store API가 있는 곳에서는 서버나 다른 탭/창에서 만든 변경도 따라가요. 호출 스코프(컴포넌트, Pinia 스토어, effectScope())와 함께 해제되고, 스코프 밖에서는 다 쓴 뒤 stop() 메서드를 호출해요 파라미터:name(string, required) 쿠키 이름 예시:'theme'options(object, optional) Ref 옵션과, ref의 모든 쓰기가 사용하는 쿠키 옵션(set() 참고) 객체 형태:default(Function, optional) 쿠키가 없을 때 ref가 읽는 값을 반환해요; ref가 생성될 때와 ref가 기본값을 다시 취할 때마다(null 할당, 제거) 호출되므로, Object나 Array 기본값은 매번 새로워져요; ref가 없는 쿠키에 부착될 때(클라이언트에서만)와 쿠키가 제거될 때마다 값이 저장돼요 함수 시그니처:() => string | object | any[]예시:() => 'light',() => ({ notifications: true })반환:string | object | any[]기본값deep(boolean, optional), 기본값trueObject나 Array 값을 반응형으로 내주어 중첩 변경이 추적되고 유지되게 해요; 값이 항상 통째로만 할당되는 것이면 false로 설정하세요disabled(boolean | object | Function, optional) true인 동안 ref는 쿠키에서 분리돼요(일반 메모리 내 ref); 다시 false가 되면 새 ref처럼 부착돼요: 쿠키가 존재하면 저장된 값이 이기고, 그렇지 않으면 현재 값이 저장돼요 예시:true,() => consent.value !== trueexpires(number | string | Date, optional) 쿠키 만료 상세; Number로 지정하면 단위는 일(day)이에요; String으로 지정하면 원시 문자열 날짜이거나 Xd Xh Xm Xs 형식일 수 있어요(예시 참고) 예시:30'Wed, 13 Jan 2021 22:23:01 GMT''1d''15m''13d''1d 15m''1d 3h 5m 3s'
path(string, optional) 쿠키 경로 예시:'/accounts'domain(string, optional) 쿠키 도메인 예시:'.foo.com'sameSite(string, optional) SameSite 쿠키 옵션 허용값:'Lax','Strict','None'httpOnly(boolean, optional) Http Only 쿠키인가요?secure(boolean, optional) 보안 쿠키인가요? (https 전용)other(string, optional) 다른 쿠키 옵션을 위한 원시 문자열; Quasar에 아직 구현되지 않은 더 새로운 props를 위한 최후의 수단으로 사용돼요 예시:'SomeNewCookieProp'반환:object쿠키에서 분리하는 추가 stop() 메서드가 있는 Vue ref
parseSSR(ssrContext: object): objectSSR/SSG에서만, 그리고 전역 import에서만 사용할 수 있어요($q.cookies에는 아님) 파라미터:ssrContext(object, required) SSR 컨텍스트 객체 반환:objectSSR/SSG 용도를 위한 쿠키 객체($q.cookies와 같음)
Vue 주입 (Vue Injection)
$q.cookies를 통해 접근할 수 있어요(예: Options API에서는 this.$q.cookies, Composition API에서는 useQuasar().cookies).
[!WARNING] Cookies 플러그인은 Electron 앱에서는 동작하지 않아요. 대신 Electron Cookies API를 사용하세요.
설치 (Installation)
quasar.config.js에 추가해요:
framework: {
plugins: [
'Cookies'
]
}
SSR/SSG에 관한 참고 (Notes on SSR/SSG)
SSR/SSG용으로 빌드할 때는 $q.cookies 형태만 사용하세요. 또는 서버 쪽일 때, 이렇게 사용할 수도 있는 한 가지 예시예요:
import { Cookies } from 'quasar'
// you need access to `ssrContext`
function (ssrContext) {
const cookies = import.meta.env.QUASAR_SERVER
? Cookies.parseSSR(ssrContext)
: Cookies // otherwise we're on client
// "cookies" is equivalent to the global import as in non-SSR/SSG builds
}
ssrContext는 @quasar/app-vite Boot File에서 사용할 수 있어요. 그리고 @quasar/app-vite preFetch 기능에서도 파라미터로 제공돼요.
이유는 클라이언트 전용 앱에서는 모든 사용자가 브라우저에서 앱의 새로운 인스턴스를 사용하기 때문이에요. 서버 사이드 렌더링에서도 같은 것을 원해요: 각 요청은 새롭고 격리된 앱 인스턴스를 가져서 요청 간 상태 오염이 없어야 해요. 그래서 Cookies는 각 요청에 별도로 바인딩되어야 해요.
쿠키 ref (Cookie refs, useCookie) (v2.34+)
useCookie(name, options)는 쿠키에 바인딩된 Vue ref를 반환해요. 읽으면 쿠키 값(없으면 그 기본값 또는 null)을 주고, 할당하면 값이 즉시 저장되며 Object나 Array 값의 중첩 변경도 저장돼요. 그것을 읽는 템플릿, computed, watcher는 앱 어디에서든 플러그인을 통해 쿠키가 변경될 때마다 다시 평가돼요. 브라우저에 Cookie Store API가 있는 곳에서는 서버, 다른 탭 또는 네이티브로 설정된 쿠키도 따라가요.
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
const theme = $q.cookies.useCookie('theme', {
default: () => 'light',
expires: '30d'
})
theme.value // 'light' while the cookie is missing, the stored value otherwise
theme.value = 'dark' // stored for 30 days; every other ref of the cookie follows
theme.value = null // removed, which reads as the default again
return { theme }
}
옵션은 모두 선택 사항이에요:
$q.cookies.useCookie('settings', {
// returns the value the ref reads while the cookie is missing; called
// each time the ref takes the default, so an Object or Array is a
// fresh one every time; the value gets stored when the ref attaches
// to a missing cookie and whenever the cookie is removed (default:
// none, the ref then reads null)
default: () => ({ notifications: true }),
// hand out an Object or Array value reactive, so that a nested change
// gets tracked and stored; false for a value that you only ever
// assign as a whole (default: true)
deep: true,
// while true the ref is detached from the cookie, a plain in-memory
// ref; once false again it attaches like a new ref (default: false)
disabled: false,
// the cookie options every write from the ref uses, as set() takes
// them (see "Write a Cookie" below); a removal carries them all but
// the expiry (default: none)
expires: '30d',
path: '/',
domain: '.example.com',
sameSite: 'Lax',
secure: true
})
예시 (Example)
예시 "쿠키 ref":
<template>
<div class="q-gutter-y-md">
<div>
Pick a theme, then reload the page: the cookie remembers the choice for a
month. In a browser with the Cookie Store API, another tab of the site
follows it too.
</div>
<q-btn-toggle
v-model="myTheme"
push
glossy
toggle-color="primary"
no-caps
:options="[
{ label: 'Light', value: 'light' },
{ label: 'Dark', value: 'dark' },
{ label: 'System', value: 'system' }
]"
/>
<div>
The cookie holds
<q-badge :label="myTheme" />
</div>
<div class="q-gutter-sm">
<q-btn
no-caps
outline
color="primary"
label="Assign 'dark'"
@click="myTheme = 'dark'"
/>
<q-btn
no-caps
outline
color="primary"
label="Assign null (back to the default)"
:disable="myTheme === 'system'"
@click="myTheme = null"
/>
</div>
</div>
</template>
<script setup>
import { useQuasar } from 'quasar'
const $q = useQuasar()
const myTheme = $q.cookies.useCookie('myTheme', {
default: () => 'system',
expires: '30d'
})
</script>
[!TIP] 컴포넌트 밖에서
useCookie()는setup()밖에서도 호출할 수 있어요: boot 파일, 스토어 또는 일반 모듈에서요. Vue effect 스코프(컴포넌트나 Pinia 스토어) 안에서 생성된 ref는 그것과 함께 해제되고, 어떤 스코프 밖에서 생성된 것은 페이지가 끝날 때까지 쿠키에 바인딩된 상태로 남아요: 다 쓴 뒤에는stop()메서드를 호출하세요.
기본값 (Defaults)
기본값이 있는 쿠키는 항상 값을 가져요. 기본값이 있는 ref가 부착된 동안 쿠키를 제거하면(remove(), null 할당, 다른 탭) 기본값이 다시 저장되므로 모든 독자가 쿠키가 무엇을 담고 있는지 일치해요. 기본값이 없는 ref는 제거된 쿠키에 대해 null을 읽어요. 기본값이 다른 같은 쿠키의 두 ref는 쿠키가 없는 동안에만 불일치하고, 먼저 부착하는 것이 정착시켜요.
객체와 배열 (Objects and Arrays)
Object나 Array는 set()처럼 JSON으로 저장되고, 새 복사본으로 다시 읽혀요: ref를 통해 만들어진 중첩 변경(settings.value.notifications = false)은 일반 Object와 Array에서만 추적되고, 각각이 전체 값을 다시 써요. 할당한 원본 객체를 변형하는 것은 아무것도 유지하지 않아요: ref를 통해 할당하세요. deep: false면 ref는 일반 값을 내주고 할당만 저장해요. ref에 할당된 Number나 Boolean은 get()이 반환하는 것처럼 String으로 다시 읽혀요.
쿠키는 속성을 포함해 약 4KB를 담고, 인코딩이 모든 중괄호, 따옴표, 콜론을 세 배로 늘린다는 점을 기억하세요. 브라우저는 받아들이지 않는 쓰기(너무 크거나, 거부하는 속성이 있는)를 조용히 버려요; 그러면 ref는 쿠키 항아리가 담고 있는 것, null 또는 기본값을 다시 읽어요.
타입 쿠키 (Typed cookies)
ref는 String이나 Object로, 또는 기본값이 주어졌을 때 그 값에 따라 타입이 정해져요(String 기본값은 String으로 타입 지정). 쿠키를 한 번 선언하면 모든 useCookie() 호출이 기본값과 유니언을 포함해 검사되게 해요:
예시 "TypeScript":
declare module 'quasar' {
interface CookieValues {
theme: 'light' | 'dark'
}
}
서버에서 (On the server)
SSR/SSG 빌드의 서버 쪽에서 $q.cookies.useCookie()는 요청 쿠키를 읽으므로 ref가 실제 값을 렌더링하고 클라이언트가 hydration에서 일치시켜요. 컴포넌트 밖에서는 SSR/SSG에 관한 참고가 다른 메서드에 대해 설명하는 것처럼 Cookies.parseSSR(ssrContext).useCookie()를 사용하세요; Cookies import 자체는 서버에서 메서드가 없어요. 그곳에서 쓰기는 set()처럼 Set-Cookie 헤더로 나가요; 없는 쿠키의 기본값은 서버가 저장하지 않고, 클라이언트가 부착할 때 저장해요. httpOnly로 설정된 쿠키는 서버가 읽고 클라이언트는 읽을 수 없는 것이므로, 렌더링된 마크업 밖에 두세요.
쿠키 읽기 (Read a Cookie)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
const value = Cookies.get('cookie_name')
쿠키가 설정되지 않았을 때 반환 값은 null이에요.
예시 "Vue 파일 안에서":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
const value = $q.cookies.get('cookie_name')
}
모든 쿠키 읽기 (Read All Cookies)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
const cookies = Cookies.getAll()
cookies 변수는 키-값 쌍(cookie_name : cookie_value)을 가진 객체이고, 각 값은 get()이 반환하는 것처럼 디코딩되고 파싱돼요.
예시 "Vue 파일 안에서":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
const allCookies = $q.cookies.getAll()
}
쿠키가 설정되었는지 확인 (Verify if Cookie is Set)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
Cookies.has('cookie_name') // Boolean
예시 "Vue 파일 안에서":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
const hasIt = $q.cookies.has('cookie_name')
}
쿠키 쓰기 (Write a Cookie)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
Cookies.set('cookie_name', cookie_value)
// or pass in options also:
Cookies.set('cookie_name', cookie_value, options)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
Cookies.set('quasar', 'framework', {
secure: true
})
예시 "Vue 파일 안에서":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.cookies.set('cookie_name', cookie_value)
// or pass in options also:
$q.cookies.set('cookie_name', cookie_value, options)
}
(선택) options 파라미터는 아래에서 속성별로 설명하는 Object예요.
옵션: expires (만료)
expires: 10 // in 10 days
expires: -1 // yesterday
expires: 'Mon, 06 Jan 2020 12:52:55 GMT'
expires: new Date() // some JS Date Object
expires: '1d 3h 5m' // in 1 day, 3 hours, 5 minutes
expires: '2d' // in 2 days
expires: '15m 10s' // in 15 minutes, 10 seconds
쿠키의 수명을 정의해요. 값은 생성 시점부터 일(day)로 해석되는 Number, Date 객체, 원시 문자열 날짜("Mon, 06 Jan 2020 12:52:55 GMT") 또는 특수 문자열 형식("1d", "15m", "13d", "1d 15m", "1d 3h 5m 3s")일 수 있어요. 생략하면 쿠키는 세션 쿠키가 돼요.
옵션: path (경로)
path: '/'
쿠키가 유효한 경로를 정의해요. 기본적으로 쿠키의 경로는 쿠키가 생성된 페이지의 경로예요(표준 브라우저 동작). 예를 들어 전체 도메인에서 사용할 수 있게 하려면 path: '/'를 사용하세요. 기본값: 쿠키가 생성된 페이지의 경로.
옵션: domain (도메인)
domain: 'quasar.dev'
쿠키가 유효한 도메인을 정의해요. 기본값: 쿠키가 생성된 페이지의 도메인.
옵션: sameSite (SameSite)
sameSite: 'Strict'
// or
sameSite: 'Lax'
SameSite 쿠키는 서버가 쿠키를 크로스 사이트(Site는 등록 가능한 도메인으로 정의) 요청과 함께 보내지 않도록 요구하게 해서, 사이트 간 요청 위조 공격(CSRF)에 대한 약간의 보호를 제공해요.
Strict - same-site 쿠키에 이 속성이 있으면 브라우저는 요청이 쿠키를 설정한 웹사이트에서 비롯된 경우에만 쿠키를 보내요. 요청이 현재 위치의 URL과 다른 URL에서 비롯된 경우, Strict 속성으로 태그된 쿠키는 전혀 포함되지 않아요.
Lax - 속성이 Lax로 설정되면 same-site 쿠키는 이미지나 프레임을 로드하는 호출 같은 크로스 사이트 하위 요청에서는 보류되지만, 사용자가 링크를 따라가는 등 외부 사이트에서 URL로 내비게이션할 때는 보내져요.
same-site 설정에 대한 자세한 내용은 여기를 참조하세요.
옵션: httpOnly
httpOnly: true
크로스 사이트 스크립팅(XSS) 공격을 완화하는 데 도움이 되도록, HttpOnly 쿠키는 JavaScript의 Document.cookie API로 접근할 수 없고 서버로만 보내져요. 예를 들어 서버 사이드 세션을 유지하는 쿠키는 JavaScript에 제공될 필요가 없으므로 HttpOnly 플래그를 설정해야 해요.
옵션: secure (보안)
secure: true
true면 쿠키 전송에 보안 프로토콜(HTTPS)이 필요하고 HTTP로는 보내지지 않아요. 기본값은 false예요.
[!TIP] Quasar CLI를 사용하고 dev 모드라면 quasar.config 파일 > devServer > https: true를 통해 HTTPS를 활성화할 수 있어요.
옵션: other (기타)
other: 'SomeNewProp'
다른 쿠키 옵션을 위한 원시 문자열이에요. Quasar에 아직 구현되지 않은 더 새로운 props를 위한 최후의 수단으로 사용돼요.
쿠키 제거 (Remove a Cookie)
예시 "Vue 파일 밖에서":
import { Cookies } from 'quasar'
Cookies.remove('cookie_name')
// if cookie was set with specific options like path and/or domain
// then you need to also supply them when removing:
Cookies.remove('cookie_name', options)
예시 "Vue 파일 안에서":
import { useQuasar } from 'quasar'
setup () {
const $q = useQuasar()
$q.cookies.remove('cookie_name')
// if cookie was set with specific options like path and/or domain
// then you need to also supply them when removing:
$q.cookies.remove('cookie_name', options)
}
[!WARNING] 쿠키가 특정
path및/또는domain으로 이전에 설정되었다면,options파라미터를 통해 remove()에 같은 속성이 전달될 때만 성공적으로 제거될 수 있어요. 이는 RFC6265을 따르는 것이에요.__Secure-또는__Host-접두사가 붙은 이름의 쿠키는 브라우저가 그 속성 없이 쓰기를 받아들이지 않으므로secure: true도 필요해요.
더 알아보기 (Learn more)
Cookies 플러그인은 document.cookie의 래퍼로, JSON 객체와 문자열을 모두 읽고 쓰며 SSR/SSG 서버 쪽 요청 쿠키도 관리해요. get/getAll/set/has/remove와 v2.34+의 useCookie()(쿠키에 바인딩된 Vue ref, 기본값·deep·disabled 옵션 지원)를 제공해요. SSR/SSG에서는 $q.cookies 형태만 쓰고 서버에서는 Cookies.parseSSR(ssrContext)를 사용하며, Electron 앱에서는 동작하지 않아요.