How to use NextJS AppRouter to get /api/auth/me on the server side
P粉883223328
2023-08-15 13:04:07
<p>I want to use app router with nextjs, and I encountered a problem. In order for my application to work, I need to call /api/auth/me to return a user, or null if not logged in. To do this, I need to include an authorization header with the bearer token obtained from localStorage in api.get("/api/auth/me") in axios. I want to do this on the server side because I need my app to display Google ads. How can I do this? </p>
<p>My layout.tsx looks like this</p>
<pre class="brush:php;toolbar:false;">import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import Sidebar from "../components/Sidebar";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="da" className="h-full bg-gray-100">
<body className="h-full bg-gray-100">
<Sidebar />
{children}
</body>
</html>
);
}</pre>
<p><br /></p>
You cannot access local storage from the server side. However, you can use cookies. For security reasons, please set http-only cookies. Therefore, you need to make a POST request after authentication to set the http-only cookie.