I try to invoke my fleet agent but seems like my Next.js code can't read my api_key environment variable so i get 401 unauthenticated error

i’m trying to invoke my Fleet agent from my website but i always get an “unauthenticated” HTTP 401 error even if my langgraph_api_key, agent_id and api_url are all correctly set as env variables in my .env.local file

i’m using Next.js and it’s only after adding a NEXT_PUBLIC_ prefix to both the api_url and agent_id that i could access them ang log both values to my console for checking, but for the api_key (personal access token) i don’t think i should add the prefix because i don’t want to expose it to the browser but the issue with that is it’s not accessible and the conclusion is i can’t invoke my fleet agent

hi @AmineAouragh

Hi! You actually diagnosed it correctly - the fix isn’t to make the key reachable from the browser, it’s to stop calling Fleet from the browser. In Next.js, anything without NEXT_PUBLIC_ is only readable on the server (Route Handlers, Server Components, Server Actions). Keep your PAT in that bucket and put a thin server endpoint in between.

1) Rename the env vars - the JS SDK auto-loads LANGGRAPH_API_KEY (then LANGSMITH_API_KEY, then LANGCHAIN_API_KEY). Lowercase langgraph_api_key won’t be picked up.

# .env.local  (all server-only - no NEXT_PUBLIC_)
LANGGRAPH_API_KEY=lsv2_pt_...
FLEET_AGENT_ID=...
FLEET_API_URL=https://<your-agent-builder-url>.us.langgraph.app

2) Add a Route Handler - app/api/agent/route.ts:

import { Client } from "@langchain/langgraph-sdk";

export const runtime = "nodejs";

export async function POST(req: Request) {
  const { message, threadId } = await req.json();

  const client = new Client({
    apiUrl: process.env.FLEET_API_URL!,
    apiKey: process.env.LANGGRAPH_API_KEY!,                    // → x-api-key
    defaultHeaders: { "X-Auth-Scheme": "langsmith-api-key" },  // required by Fleet
  });

  const result = await client.runs.wait(
    threadId ?? null,
    process.env.FLEET_AGENT_ID!,
    { input: { messages: [{ role: "user", content: message }] } },
  );
  return Response.json(result);
}

3) Call your own endpoint from the client - fetch("/api/agent", { method: "POST", body: ... }). No SDK, no key in the browser.

Why you were getting 401 specifically: even with a valid PAT, Fleet needs both X-Api-Key and X-Auth-Scheme: langsmith-api-key. Missing the scheme header alone produces a 401. The SDK turns apiKey into x-api-key automatically, but you have to add X-Auth-Scheme yourself via defaultHeaders-— exactly as shown in the docs.

Other things that bite people with this same 401:

  • Reading process.env.LANGGRAPH_API_KEY inside a "use client" file → it’s undefined there.
  • Forgot to restart next dev after editing .env.local.
  • Using https://api.smith.langchain.com instead of the deployment URL from Fleet → Settings → View code snippets.
  • If you ever briefly set NEXT_PUBLIC_LANGGRAPH_API_KEY, rotate the PAT - assume it leaked into a bundle.

If your app is multi‑tenant, the cleaner long‑term option is custom auth on the deployment so each user sends their own JWT instead of a shared PAT - see LangGraph Platform auth docs.

Refs: Fleet - Call agents from your app · Next.js env vars

Thanks a lot for the help. The problem was actually related to not building an api endpoint properly. Now it’s done and my frontend can connect to the Fleet agent BUT now there is another problem.

I built a competitor research agent and I tested it from Langsmith UI and it works perfectly, I just describe a business idea in the chat and it’s doing competitor research and returning 3 direct competitors in json format.

But from my website with an api call it does return a result but not what’s expected

Instead of getting the expected result from my agent I only get a JSON including metadata about system skills, the LLM model used, etc… all useless for my use case.

I used the right code to invoke agent from the langsmith docs but still.

The “useless metadata” isn’t a different API response - it’s the full LangGraph state that runs.wait returns. The UI hides that plumbing for you; the API hands you everything: messages, files (your system-skills/*/SKILL.md is the Deep Agents virtual FS - deepagentsjs/libs/deepagents/src/types.ts:572-581), usage_metadata, etc.

Do you have any tool registered for you agent?

I understand but what I actually need to get in return is a JSON with the following content

{"category":"AI video clipping / long-form-to-shorts with auto subtitles","competitors":[{"name":"OpusClip","website":"https://www.opus.pro/","positioning":{"confirmed":"Markets itself as the '#1 AI video clipping tool' that turns one long video into multiple viral clips and publishes them to social platforms.","interpretation":"Most directly positioned around automated repurposing from podcasts, webinars, interviews, and creator content into short-form social video."},"target_users":{"confirmed":["Creators","Podcasters","Marketers","Agencies","Livestreamers","Media & entertainment teams"],"interpretation":"Broad horizontal go-to-market spanning solo creators to business teams."},"product":{"confirmed":["AI clipping / highlight extraction","Animated captions","AI reframe for resizing to vertical formats","AI B-roll","AI video editor","Social scheduler","Brand templates","Export to XML for Premiere/DaVinci","Team workspace"],"interpretation":"Strongest 'all-in-one repurposing suite' among direct competitors, not just a single clipper."},"pricing":{"model":"Free trial + subscription","plans":[{"name":"Free / trial signal","price":"7-day Pro trial with 90 minutes processing time (~30 downloadable clips)","billing_period":"trial","notes":"Site states OpusClip is free to use and new users get a 7-day Pro trial."}],"interpretation":"Likely monetizes on processing minutes / premium workflow features rather than pure seat access."},"strengths":["Very clear value prop around turning 1 long video into many clips","Strong feature breadth beyond clipping","Built-in publishing/scheduling narrative","Strong social proof and multi-segment messaging"],"weaknesses":["Broad product scope may make it feel less focused for niche users","Pricing transparency on homepage is limited from captured source","Positioning leans heavily on virality claims, which can create skepticism"],"recent_signals":["Homepage emphasizes multi-platform publishing and growth outcomes","Product nav shows expanded suite: captions, reframe, B-roll, scheduler, brand templates, editor"],"sources":["https://www.opus.pro/"]},{"name":"Vizard","website":"https://vizard.ai/","positioning":{"confirmed":"Promotes itself as an AI video editing and clipping tool that turns long-form videos into short clips for TikTok, Instagram, YouTube Shorts, and more.","interpretation":"Competes as a simpler, creator-friendly/browser-based alternative focused on clipping plus editing."},"target_users":{"confirmed":["Marketers","Creators","Agencies","Podcasters","Coaches","Consultants"],"interpretation":"Targets both teams and individual creators, with strong appeal to users who want easier editing after AI clipping."},"product":{"confirmed":["Long-form to short clip generation","AI video editing","Text-based editing","Video repurposing","Subtitles","Upload or paste YouTube link","Social-ready short clips"],"interpretation":"More editing-forward than OpusClip, with clipping as part of a broader lightweight editor workflow."},"pricing":{"model":"Subscription (not verified from current page read)","plans":[],"interpretation":"Pricing likely exists on /pricing, but concrete plan amounts were not recovered from the source pages used here."},"strengths":["Clear long-form to shorts use case","Accessible editor + clipping combo","Strong trust/social proof on homepage","Good fit for marketers and teams wanting less complexity"],"weaknesses":["Less explicit enterprise/workflow breadth than OpusClip from observed pages","Pricing details not easily extracted from available source content","May feel less differentiated if many rivals also offer captions + reframing"],"recent_signals":["Homepage now also highlights an 'AI studio' with additional generation models","Still keeps clipping/repurposing as core homepage message"],"sources":["https://vizard.ai/"]},{"name":"quso.ai (formerly vidyo.ai)","website":"https://quso.ai/","positioning":{"confirmed":"Presents itself as a social media AI platform that includes AI Clips Generator, AI Subtitle Generator, AI Video Editor, repurposing, scheduling, and analytics.","interpretation":"Broader 'social media copilot' positioning than pure clipping; strongest for users who want clip creation plus downstream distribution."},"target_users":{"confirmed":["Content creators","Podcasters","Marketing managers","Freelancers","Small businesses","Startups","Agencies","Coaches"],"interpretation":"Targets users who need end-to-end content repurposing and social publishing, not just clip extraction."},"product":{"confirmed":["AI Clips Generator","AI Subtitle Generator","AI Video Editor","Long to Short Video AI","Resize Video","Social media scheduling","Social analytics","AI captions / writing tools"],"interpretation":"Closest competitor if your product combines clipping + subtitles + publishing workflow."},"pricing":{"model":"Subscription","plans":[],"interpretation":"Pricing page exists, but numeric plan details were not reliably extracted from the page content reviewed."},"strengths":["Very broad suite spanning create/edit/schedule/analyze","Strong subtitle and clip tooling fit for the described use case","Formerly vidyo.ai gives it existing brand recognition in AI clipping"],"weaknesses":["Positioning may be too broad if user only wants best-in-class clipping","Rebrand from vidyo.ai to quso.ai may create some market confusion","Could be perceived as more social-suite than specialist clipper"],"recent_signals":["Brand transition to quso.ai from vidyo.ai","Navigation heavily emphasizes clips, subtitles, long-to-short video, and scheduling"],"sources":["https://quso.ai/pricing","https://quso.ai/"]}],"summary":{"direct_competitor_take":"The three most relevant direct competitors are OpusClip, Vizard, and quso.ai/vidyo.ai.","market_pattern":"This category is converging on the same core bundle: AI highlight detection + auto vertical reframing + auto subtitles + light editing + optional scheduling/publishing.","positioning_gap":"A viable opening is to be more opinionated or specialized than these players—e.g. best for podcasts, coaches, agencies, fastest human-in-the-loop workflow, better subtitle styling, or better clip quality/brand consistency rather than just 'viral clips'.","pricing_gap":"Competitors signal subscription pricing and free entry/trial, but public pricing clarity is inconsistent from surfaced sources. Transparent usage-based pricing could differentiate."},"uncertainty":["Exa search was unavailable due to missing API key, so research relied on Tavily plus direct page reads.","Concrete up-to-date paid plan prices for Vizard and quso.ai were not reliably extractable from the fetched pages, so only pricing model/trial signals are included where confirmed."]}

Just like I get in the Langsmith UI playground

From my website UI I have a text field where i just describe a business idea and if i click “start”, the agent is invoked, should do the competitor research and then return in result the json with competitors insights not metadata about the model used or tokens used or whatever.

@AmineAouragh I don’t see your last message

Hey man it’s because my post got flagged by someone for some reason but now the staff restored it back, you can now see it

alright, I see it now