search

Home  >  Q&A  >  body text

How to use API routing in NextJS 13

When using Express, I used to store users like request.user:

import jwt from "jsonwebtoken"; 
import asyncHandler from "express-async-handler"; 
import User from "../models/userModel.js";

const protect = asyncHandler(async (req, res, next) => {
  let token;
  token = req.cookies.jwt;
  if (token) {
    try {
      const decoded = jwt.verify(token, process.env.JWT_SECRET);
      req.user = await User.findById(decoded.userId).select("-password");
      next();
    } catch (error) {
      res.status(401);
      throw new Error("Not authorized , invalid token");
    }
  } else {
    res.status(401);
    throw new Error("Not authorized , no token");
  }
});

export { protect };

And I was able to get the current user like this : 

const createPost = asyncHandler(async (req, res) => {
  const { content, image } = req.body;
  const user = req.user;

But how to do this using NextJS 13 API routing and middleware and how to use cookies. New to NextJS so any help would be greatly appreciated.

P粉903969231P粉903969231449 days ago654

reply all(1)I'll reply

  • P粉176980522

    P粉1769805222023-09-08 00:18:14

    In Next.js, you can use the cookie extensions on NextRequest and NextResponse to read and manipulate cookies. The specific method is as follows:

    First, you need to import cookies from next/headers:

    import { cookies } from 'next/headers'

    Then, you can get a cookie like this:

    const cookieStore = cookies()
    const token = cookieStore.get('token')

    To set a cookie, you need to return a new response using the Set-Cookie header:

    return new Response('Hello, Next.js!', {
      status: 200,
      headers: { 'Set-Cookie': `token=${token}` },
    })

    You can also use the NextRequest object to read cookies:

    export async function GET(request) {
      const token = request.cookies.get('token')
    }

    For incoming requests, cookies have the following methods: get, getAll, set and delete cookies. You can use has to check if a cookie exists, or clear to delete all cookies.

    For outgoing responses, the cookie has the following methods get, getAll, set and delete.

    Here are examples of how to use these methods:

    import { NextResponse } from 'next/server'
    import type { NextRequest } from 'next/server'
    
    export function middleware(request: NextRequest) {
      let cookie = request.cookies.get('nextjs')
      console.log(cookie) // => { name: 'nextjs', value: 'fast', Path: '/' }
      const allCookies = request.cookies.getAll()
      console.log(allCookies) // => [{ name: 'nextjs', value: 'fast' }]
    
      request.cookies.has('nextjs') // => true
      request.cookies.delete('nextjs')
      request.cookies.has('nextjs') // => false
    
      const response = NextResponse.next()
      response.cookies.set('vercel', 'fast')
      response.cookies.set({
        name: 'vercel',
        value: 'fast',
        path: '/',
      })
      cookie = response.cookies.get('vercel')
      console.log(cookie) // => { name: 'vercel', value: 'fast', Path: '/' }
    
      return response
    }

    reply
    0
  • Cancelreply