Created
September 11, 2023 11:30
-
-
Save mustafadalga/fde00871063edfa601dfa7497f671502 to your computer and use it in GitHub Desktop.
Sending Cookie to API Route in Next.js 13:In a Next.js 13 project, you can send a cookie to an API route by including it in the headers of your Axios request in your server-side function. In the API route, you can access this cookie using request.cookies.get('cookieName').
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NextRequest, NextResponse } from "next/server"; | |
import { AxiosInstance } from "axios"; | |
import { CookieKeys } from "@/_enums"; | |
import createAuthenticatedApiServiceV2 from "@/_services/createAuthenticatedApiServiceV2"; | |
import handleAxiosError from "@/_utilities/handleAxiosError"; | |
export async function GET(request: NextRequest) { | |
try { | |
const jwt: string | undefined = request.cookies.get(CookieKeys.Jwt)?.value; | |
if (!jwt) { | |
return NextResponse.json({ message: "You are not authorized to access this resource." }, { status: 403 }); | |
} | |
// remain code.... | |
} catch (error) { | |
console.log(error) | |
const { | |
message, | |
status | |
} = handleAxiosError(error, "Oops! Something went wrong while listing posts. Please refresh the page and try again!"); | |
return NextResponse.json({ message }, { status }); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import axios from "axios"; | |
import handleAxiosError from "@/_utilities/handleAxiosError"; | |
import { cookies } from "next/headers"; | |
import { CookieKeys } from "@/_enums"; | |
export default async function getPosts() { | |
try { | |
const jwt = cookies().get(CookieKeys.Jwt)?.value | |
const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}api/post/list`; | |
const { data } = await axios.get(url, { | |
params: { | |
isCustom: true | |
}, | |
headers: { | |
'Cookie': `jwt=${jwt};` | |
}, | |
}); | |
return { | |
data, | |
status: true | |
}; | |
} catch (error) { | |
const defaultMessage = "Oops! Something went wrong while loading posts. Please try again later."; | |
const { message: data } = handleAxiosError(error, defaultMessage); | |
return { | |
data, | |
status: false | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment