Prevent change the cookie from javascript or console.log in the browser

So I have some composable named useAuth served as the provider to set, get, and remove the token from cookie. But I want this cookie can't be changed from the browser or console.log, is it possible?
export default function useAuth() {

const setAuthorizationToken = async (val: string, expiresAt?: any) => {
let expiryDate: Date;

if (!expiresAt) {
// Default expiration: 1 month from now
expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 1);
} else if (typeof expiresAt === "string" || typeof expiresAt === "number") {
// Parse `expiresAt` if it's a timestamp or ISO string
expiryDate = new Date(expiresAt);
} else if (expiresAt instanceof Date) {
// Use `expiresAt` directly if it's already a Date object
expiryDate = expiresAt;
} else {
throw new Error("Invalid expiresAt format. Expected a Date, timestamp, or ISO string.");
}

const token = useCookie("_at", {
path: "/",
expires: expiryDate,
sameSite: "strict", // Tidak dikirim ke domain lain
});
token.value = val;
}
}
export default function useAuth() {

const setAuthorizationToken = async (val: string, expiresAt?: any) => {
let expiryDate: Date;

if (!expiresAt) {
// Default expiration: 1 month from now
expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 1);
} else if (typeof expiresAt === "string" || typeof expiresAt === "number") {
// Parse `expiresAt` if it's a timestamp or ISO string
expiryDate = new Date(expiresAt);
} else if (expiresAt instanceof Date) {
// Use `expiresAt` directly if it's already a Date object
expiryDate = expiresAt;
} else {
throw new Error("Invalid expiresAt format. Expected a Date, timestamp, or ISO string.");
}

const token = useCookie("_at", {
path: "/",
expires: expiryDate,
sameSite: "strict", // Tidak dikirim ke domain lain
});
token.value = val;
}
}
5 Replies
kapa.ai
kapa.ai4d ago
Hi @Adnan Erlansyah. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- To prevent the cookie from being changed via JavaScript or viewed in the browser console, you can use the httpOnly flag when setting the cookie. This flag ensures that the cookie is only accessible by the server and not by client-side scripts. Here's how you can modify your useAuth composable to achieve this:
export default function useAuth() {
const setAuthorizationToken = async (val: string, expiresAt?: any) => {
let expiryDate: Date;

if (!expiresAt) {
// Default expiration: 1 month from now
expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 1);
} else if (typeof expiresAt === "string" || typeof expiresAt === "number") {
// Parse `expiresAt` if it's a timestamp or ISO string
expiryDate = new Date(expiresAt);
} else if (expiresAt instanceof Date) {
// Use `expiresAt` directly if it's already a Date object
expiryDate = expiresAt;
} else {
throw new Error("Invalid expiresAt format. Expected a Date, timestamp, or ISO string.");
}

const token = useCookie("_at", {
path: "/",
expires: expiryDate,
sameSite: "strict",
httpOnly: true, // Add this line
secure: true // Add this line if your site uses HTTPS
});
token.value = val;
}
}
export default function useAuth() {
const setAuthorizationToken = async (val: string, expiresAt?: any) => {
let expiryDate: Date;

if (!expiresAt) {
// Default expiration: 1 month from now
expiryDate = new Date();
expiryDate.setMonth(expiryDate.getMonth() + 1);
} else if (typeof expiresAt === "string" || typeof expiresAt === "number") {
// Parse `expiresAt` if it's a timestamp or ISO string
expiryDate = new Date(expiresAt);
} else if (expiresAt instanceof Date) {
// Use `expiresAt` directly if it's already a Date object
expiryDate = expiresAt;
} else {
throw new Error("Invalid expiresAt format. Expected a Date, timestamp, or ISO string.");
}

const token = useCookie("_at", {
path: "/",
expires: expiryDate,
sameSite: "strict",
httpOnly: true, // Add this line
secure: true // Add this line if your site uses HTTPS
});
token.value = val;
}
}
By adding the httpOnly: true option, you prevent the cookie from being accessed or modified by JavaScript in the browser. This means it cannot be changed via the console or client-side scripts. Additionally, I've added the secure: true option, which ensures that the cookie is only sent over HTTPS connections. This is recommended for security-sensitive cookies like authentication tokens. It's important to note that while this prevents client-side access to the cookie, it doesn't make the cookie completely tamper-proof. The cookie can still potentially be modified by users with access to the client machine or through man-in-the-middle attacks if not using HTTPS. For the highest level of security, consider using server-side sessions in combination with HttpOnly, Secure cookies, and implement additional security measures like CSRF protection. Docs > Api > Composables > useCookie provides more information about the httpOnly and other security-related options for cookies in Nuxt. Remember that with this configuration, you won't be able to access the cookie value directly in your client-side JavaScript. You'll need to rely on server-side logic or API calls to handle operations that require the token. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Adnan Erlansyah
Adnan ErlansyahOP4d ago
@kapa.ai But when I want to set the cookie with the same name again, I got this error.
Cookie “_at” has been rejected because there is already an HTTP-Only cookie but script tried to store a new one.
Cookie “_at” has been rejected because there is already an HTTP-Only cookie but script tried to store a new one.
kapa.ai
kapa.ai4d ago
Let me check the knowledge base for you again. One moment! :books: ---------------------- This error occurs because you're trying to set a cookie with the same name ("_at") that already exists as an HTTP-Only cookie. The browser is preventing this action as a security measure to protect the existing HTTP-Only cookie from being overwritten by client-side scripts. To resolve this issue, you have a few options: 1. Use a different name for the client-side cookie: If you need to set a separate cookie from the client side, use a different name to avoid conflicts with the HTTP-Only cookie. 2. Update the cookie server-side: Since the existing cookie is HTTP-Only, you should update it on the server side. You can do this by creating an API endpoint that updates the cookie. 3. Remove the existing cookie before setting a new one: If you're intentionally trying to replace the existing cookie, you need to remove it first. However, since it's HTTP-Only, you'll need to do this server-side as well. Here's an example of how you might update the cookie server-side:
// server/api/updateAuthToken.ts
import { defineEventHandler } from 'h3'

export default defineEventHandler((event) => {
const newToken = 'your-new-token-value'

setCookie(event, '_at', newToken, {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/',
// Set other options as needed
})

return { success: true }
})
// server/api/updateAuthToken.ts
import { defineEventHandler } from 'h3'

export default defineEventHandler((event) => {
const newToken = 'your-new-token-value'

setCookie(event, '_at', newToken, {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/',
// Set other options as needed
})

return { success: true }
})
Then, in your client-side code, instead of directly setting the cookie, you would call this API:
const updateToken = async (newToken: string) => {
await $fetch('/api/updateAuthToken', {
method: 'POST',
body: { token: newToken }
})
}
const updateToken = async (newToken: string) => {
await $fetch('/api/updateAuthToken', {
method: 'POST',
body: { token: newToken }
})
}
This approach maintains the security of your HTTP-Only cookie while allowing you to update it as needed. Remember, the purpose of an HTTP-Only cookie is to prevent client-side access, so you should design your authentication flow to work with this limitation. If you find yourself frequently needing to update the cookie from the client side, you might want to reconsider your authentication strategy. Docs > Api > Composables > useCookie > Cookies in API Routes provides more information about handling cookies in server-side API routes in Nuxt. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4d ago
<@1079709612078534676> Kapa.ai is still learning and improving, please let me know how I did by reacting below.

Did you find this page helpful?