Exploring Next.js 13: Enhancing Security with HTTP Cookie Authentication

I'm currently working on a web app using Next.js version 13.4.7. I am setting up authentication with JWT tokens from the backend (Laravel) and attempting to store them in http-only cookies.

Within a file named cookie.ts, which contains helper functions, there are two functions - one for setting the cookie after receiving it from the backend, and another for retrieving the cookie from the browser.

export const setAuthToken = (
    expiresIn: number,
    accessToken: string | null,
    baseUrl: string
) => {
    return fetch(`${baseUrl}/api/auth/login`, {
        method: "post",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ expiresIn, accessToken }),
    });
};

export const getAccessTokenCookie = async (baseUrl: string) => {
    const response = await fetch(`${baseUrl}/api/auth/login`, {
        method: "get",
    });
    const data = await response.json();
    console.log(data, "data");

    return data.token;
};

The setAuthToken function sends a fetch request to /app/api/auth/login/route.ts.

import { cookies } from "next/headers";

export async function POST(request: Request) {
    const body = await request.json();
    const { expiresIn, accessToken } = body;
    cookies().set({
        name: "access_token",
        value: accessToken,
        httpOnly: true,
        secure: process.env.NODE_ENV !== "development",
        sameSite: "strict",
        maxAge: expiresIn,
        path: "/",
    });
}

export async function GET() {
    const accessToken = cookies().get("access_token");
    console.log(accessToken, "accessToken");

    if (!accessToken?.value) {
        return new Response(JSON.stringify({ token: null }), {
            headers: {
                "Content-Type": "application/json",
            },
        });
    }
    return new Response(JSON.stringify({ token: accessToken.value }), {
        headers: {
            "Content-Type": "application/json",
        },
    });
}

Although the POST request in setAuthToken successfully creates and stores the cookie, when attempting to retrieve it through getAccessTokenCookie, the cookie cannot be found, even within the GET function of the route.ts file.

Answer №1

This particular cookies instance is in a read-only state. If you want to update the cookies, you have to create a new Response object and include the Set-Cookie header.

For more information, you can visit this link.

Answer №2

Incorporate the given return statement into your post function:

return new Response(JSON.stringify({success:true}));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing this peculiar behavior in my React/TypeScript/MUI Dialog?

My React/TypeScript/MUI application has a dialog that displays multiple buttons. Each time a button is clicked, the dialog function adds the button value to a state array and removes it from the dialog. Although it seems to be working, there is an issue wh ...

Exploring end-to-end testing with NestJS and Guards

I'm trying to test an endpoint called /users using nestjs, but I encountered some errors. I'm unsure how to fix the issues and make the test pass with a guard. First Issue Nest is unable to resolve dependencies of the UserModel (?). Please en ...

Discovering the name of an object property by locating its corresponding id

I am working with a basic JSON data structure where I need to retrieve the name from an object by comparing its ID. For example, if I have the number 2, I need to check if it matches any object's ID. If the ID is equal to 2, then I must fetch the corr ...

Is there a simple method within my login script to generate an admin session effortlessly?

Hey there, take a look below at my login script that I'm looking to add an "isAdmin" feature to. <?php session_start(); $username = "#####"; $password = "#####"; $hostname = "#####"; $dbhandle = mysq ...

Invoking a function on an object of a subclass that derives from an abstract class

In the realm of abstract classes, behold this one: export abstract class BaseStepComponent { /** Behold thy base-step ctor */ constructor() { } abstract getValue(): string; } And lo, here is a component that inherits such abstract glory ...

Dealing with connection issues: How to handle ECONNREFUSED error when using MSW with React Testing Library in a NextJS project

Struggling to successfully mock the SWR fetch API call using MSW. To reproduce this issue, refer to the repository linked here: https://github.com/charitha95/msw-test Encountering the following error when using MSW: Error: connect ECONNREFUSED 127.0. ...

The Event Typing System

I am currently in the process of setting up a typed event system and have encountered an issue that I need help with: enum Event { ItemCreated = "item-created", UserUpdated = "user-updated", } export interface Events { [Event.Ite ...

Error: It seems that in your next.js + expo project, you may have overlooked properly exporting your component from its defined file, or there could be confusion between default and named imports

Whenever I attempt to execute yarn ios, the following error message appears: An issue arose with the element type, as it is invalid. The expected input should be a string for built-in components or a class/function for composite components, yet it receive ...

The error being thrown is related to Next.js 13 cache setting of 'no-store'

Check out this snippet of code async function fetchData() { const response = await fetch('http://127.0.0.1:1337/api/posts', { method: 'GET', headers: { 'Content-Type': 'application/json', Author ...

How to access the component instance in Angular through router events

I am currently working on incorporating a title service into my Angular 10 application. My goal is to subscribe to router events, access the activated route's component, check if it has a title() getter, and then use that information to set the page&a ...

Do not use the .map method! Caution: Every child component in a list must be assigned a unique "key" prop

I have recently started working with NEXT JS and I am encountering a peculiar issue for which I haven't been able to find a solution online. The warning message I'm getting is: "Each child in a list should have a unique key prop." Warning: Each c ...

Creating a dynamic array in an Angular 2 service for real-time changes monitoring by a component

I am facing an issue where my NotificationsBellComponent is not receiving changes to the array in the service even though the _LocalStorageService is returning data correctly. Q) How can I ensure that my component receives updates when the service collect ...

Is it possible to utilize the $ symbol within the ngOnInit or constructor functions?

I recently encountered an issue while trying to use the dollar sign ($) in my constructor function, specifically within ngOnInit() and translate.instant. Here is a snippet of the code that caused the problem: declare var $: any; { var SelectedDevice = ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

"Exploring the world of Typescript with the Drawflow library

Currently, I am integrating the fantastic Drawflow library created by @Jerosoler (available at: https://github.com/jerosoler/Drawflow) into my PrimeNg project. User @BobBDE has provided typescript definitions for this library here: https://www.npmjs.com/p ...

Aurelia's navigation feature adds "?id=5" to the URL instead of "/5"

I have set up my Aurelia Router in app.ts using the configureRouter function like this: configureRouter(config, router: Router) { config.map([ { route: ['users', 'users/:userId?'], na ...

What is the best way to change the number 123456789 to look like 123***789 using either typescript or

Is there a way to convert this scenario? I am working on a project where the userID needs to be displayed in a specific format. The first 3 characters/numbers and last 3 characters/numbers should be visible, while the middle part should be replaced with ...

Is it achievable to dynamically generate new pages on initial load in NextJS?

Right now, I am utilizing getStaticProps and getStaticPaths to pre-render a specific number of articles before my website goes live. This method works effectively, but if a new article is created and displayed on the front page while the site is still acti ...

How to format dates with month names in various languages using the date pipe

In my HTML code, I have set up the date display like this: <span >{{ item.lastModified | date : 'MMM d, y' }}</span> As a result, the displayed date looks something like Jul 20, 2021. However, when I switch my browser's language ...

Creating asynchronous JavaScript constructors using a static method called "create" presents challenges when dealing with TypeScript types

I've been diving into the world of asynchronous constructors and have successfully implemented them in JavaScript. However, I'm facing a challenge with TypeScript types. Here's how it should ideally work: const a: AnyClass = await AnyClass. ...