Next.js: Adding res.cookie and res.clearCookie in API Routes

Created on 12 Jul 2019  路  7Comments  路  Source: vercel/next.js

Feature request

Is your feature request related to a problem? Please describe.

Having res.cookie and res.clearCookie helper function makes it easier to manipulate cookies in response.

Describe the solution you'd like

Implementing ExpressJS-like res.cookie and res.clearCookie

Describe alternatives you've considered

Using http.ServerResponse response.setHeader(name, value)

Additional context

If this is not possible, how can I implement my own res.cookie and res.clearCookie using middlewares?

feature request needs investigation

Most helpful comment

@XOKP I cleared the cookie this way

res.setHeader(
      "Set-Cookie",
      "token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
    );

Source

All 7 comments

It will be nice if we are able to use express middleware.

I'm closing this issue as it has been solved using Middleware. Thanks @huv1k for that.

api-routes-middleware

Still, I wish we include it in the core of API Routes since we have already has req.cookies anyway. But I understand that it may make API Routes too opinionated.

I'm closing this issue as it has been solved using Middleware. Thanks @huv1k for that.

api-routes-middleware

Still, I wish we include it in the core of API Routes since we have already has req.cookies anyway. But I understand that it may make API Routes too opinionated.

The middleware does not has the clearCookie function...

@XOKP I cleared the cookie this way

res.setHeader(
      "Set-Cookie",
      "token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT"
    );

Source

I can't reproduce api-routes-middleware in Typescript because NextApiResponse is a type but not an interface, and property cookie can not be added to res

@edshav It is possible with TS, TS now supports extending interface from an object type. I used following and TS didn't gave any error to me.

interface NextResponse extends NextApiResponse {
  cookie(name: string, value: string, options?: CookieSerializeOptions): void
}

Hi @farhantahir do you know how can we extend NextApiResponse but preserving the same name? There's no problem with NextApiRequest because that is already an interface.

Was this page helpful?
0 / 5 - 0 ratings