Next.js Discord

Discord Forum

[auth.js] I dont know how to access protected apis from nextjs client to /api route

Unanswered
Kawakawa posted this in #help-forum
Open in Discord
KawakawaOP
I have been trying to access the protected api /api/protected/containers but if i access that route in my browser it gives output. but if i acccess it thro fetch() in page.tsx, it gives 401 not authenticated


/api/protected/connectors
import { auth } from "auth"
import { ConnectorType } from "@/lib/connectorDef"

let connectors: ConnectorType[] = [
    {
        name: "Google Sheets",
        typeOfDoc: "REST API",
        baseUrl: "https://sheets.googleapis.com",
        category: "Productivity",
        pathToParentFolder: "google",
        ...
    }
]

export const GET = auth((req) => {
  if (req.auth) {
    return Response.json({ data: connectors }, { status: 200 })
  }

  return Response.json({ message: "Not authenticated" }, { status: 401 })
}) as any // TODO: Fix `auth()` return type


page.tsx
import CustomLink from "@/components/custom-link"
import SessionData from "@/components/session-data"
import Connectors from "@/components/connectors"
import { ConnectorType } from "@/lib/connectorDef"
import { auth } from "auth"

export default async function Page() {
  const session = await auth()
  if (session) {
    const response = await fetch(`http://localhost:3000/api/protected/connectors`)
    const connectors = await response.json() as ConnectorType[]
    console.log(connectors)
    return (
      <div className="space-y-2">
        hi
      </div>
    )
  } else {
    return <>Login To continue</>
  }
}


error:
 GET /api/protected/connectors 401 in 6ms
{ message: 'Not authenticated' } 

10 Replies

KawakawaOP
yeah ig i was missing the ...
it works
thanks
auth.js is too hard for me. i am familiar with next13 and next auth back at 2024 jan-march, then this week i am seeing nextjs 15 and auth.js with less documentation on how to follow..

literally their google adapter, if i follow from the doc, dosent even work.. somehow now everything works now
KawakawaOP
i'll check them out! thanks :))
@Yi Lon Ma try adding `fetch(..., {credentials:true})`
KawakawaOP
Found the real issue..

In server side fetchings, we have to mention the full URL in order for fetch to work
for client side things, we dont have too - https://github.com/vercel/next.js/issues/48344
thats why we have to mention credentials explicitly
ig server side props are better than fetch