September 18, 2026
Understanding types/auth.ts and actions/auth.ts - How a Next.js Frontend and a Go Backend Agree on Data


This guide walks through two real files from a working project: a Next.js 16 (App Router) frontend, and a Go + Gin backend, talking to each other over plain JSON.
You do not need to know Go to follow this. You only need to know: Go is a separate program, running on a separate computer (or a separate process on your own machine), and the only way it can talk to your Next.js app is by sending text back and forth over the internet.
backstory
Here is the one idea this whole guide is built on:
Your frontend and your backend cannot see each other's code. TypeScript cannot look inside a Go file and know what shape of data it sends back. All it gets is plain text (JSON) over HTTP. Everything else - every type, every function in these two files - exists to make that plain text safe to work with.
Two files do two very different jobs to solve this:
types/auth.ts- describes, in TypeScript, exactly what shape every piece of data is. It does nothing at runtime. It is pure description like a packing list.actions/auth.ts- does the actual work. It sends the real HTTP request to Go, waits for the reply, and turns that reply into a shape your app can always rely on - whether Go said yes or no.
We'll go through both, slowly, with real code from the project.
the big picture
Before the details, here's the shape of the whole system. Keep this picture in your head β everything below is one piece of it.
Your form (React)
|
v
actions/auth.ts β sends the real request, using axios
|
v
Go + Gin β the backend, a completely separate program
|
v
actions/auth.ts β reads Go's reply, rebuilds it into a safe shape
|
v
Your form (React) β always gets the same {success, message, error, status} shape
types/auth.ts doesn't appear as a "step" in that picture β it's the rulebook every step in that picture has to follow.
prerequisites
To follow this guide comfortably, it helps to already know:
- Basic TypeScript: what an
objecttype looks like, what?(optional) means on a property - What JSON is, and that HTTP requests/responses carry JSON as plain text
- That this project's frontend is Next.js 16 (App Router) and the backend is Go + Gin
You do not need to already understand generics (<T>) or intersection types (&) - we explain both from scratch below, with plain-English analogies before any code.
This project uses bun, but the same commands work with pnpm or npm - every command below is shown for all three.
step 1 - two files, two very different jobs
Think of types/auth.ts and actions/auth.ts like this:
types/auth.tsis a description.actions/auth.tsis an action. One tells TypeScript what things look like. The other actually goes and gets them.
types/auth.ts never runs. It disappears completely once your code is compiled - TypeScript types exist only to catch mistakes while you're writing code, not while the app is running. actions/auth.ts is the opposite: it's real, running code that makes a real network call every time someone calls it.
step 2 - types/auth.ts, part one: describing what Go actually sends
This part of the file is what we call the wire shapes - "wire" as in "the wire the data travels over." These types describe Go's JSON honestly, with nothing tidied up or added.
the envelope
Every response from this Go backend is wrapped the same way - like every letter arriving in the same style of envelope, whatever is inside it:
export type BackendEnvelope<T = never> = {
success: boolean;
message: string;
error?: string;
data?: T;
};Four fields:
success- did it work? Always present.message- a human-readable sentence, always present ("Account created!", "Invalid email or password").error?- only shows up when something went wrong. The?means "this key might not exist at all" β not "this key exists but is empty."data?- the actual payload for this specific endpoint, if there is one. Some endpoints (like forgot-password) just send a message with no extra data at all.
what <T = never> means
<T> is a generic - think of it as a fill-in-the-blank on a form. BackendEnvelope doesn't know, by itself, what kind of data each endpoint sends. T is the blank that gets filled in differently depending on which endpoint you're describing:
BackendEnvelope<BackendUserData> // "data holds a BackendUserData"
BackendEnvelope<BackendLoginData> // "data holds a BackendLoginData"
BackendEnvelope // no blank filled in β uses the defaultThat last line - no angle brackets at all - only works because of = never. This is exactly like a default value on a function parameter:
function greet(name: string = "friend") { ... }
greet() // name = "friend"
greet("Sam") // name = "Sam"= never says: if nobody fills in the blank, use never. And never is the right choice here - not unknown, not undefined - because some Go endpoints (forgot-password, reset-password, resend-verification) genuinely send no extra data at all. never means "this slot cannot legitimately hold a real value," which is an honest description of those endpoints.
In plain words:
BackendEnvelopeis "exactly what Go's letter looks like when it arrives" - including the parts that aren't always there.
the user data shape
export type BackendUserData = {
id: string;
first_name?: string;
last_name?: string;
email?: string;
role?: string;
avatar?: string;
job_title?: string;
active?: boolean;
provider?: string;
created_at?: string;
updated_at?: string;
};Notice the field names: first_name, not firstName. That's snake_case, and it's here because Go's own struct tags write JSON keys that way (json:"first_name"). This type is a direct mirror of what Go actually serializes - nothing renamed, nothing cleaned up yet. Only id is required; everything else is optional, because two different Go endpoints send different subsets of these fields.
combining two shapes with &
export type BackendLoginData = BackendUserData & {
token: string;
expires_in?: number;
};& is an intersection type. It means: take every field from the left side, take every field from the right side, and merge them into one flat object that has all of them. Expanded by hand, BackendLoginData is exactly:
{
id: string; first_name?: string; last_name?: string; email?: string;
role?: string; avatar?: string; job_title?: string; active?: boolean;
provider?: string; created_at?: string; updated_at?: string;
token: string; expires_in?: number;
}One flat object, thirteen fields - because that's genuinely how Go sends it: the user's info and the login token together, in one JSON object, not nested inside each other.
Writing it with & instead of retyping all thirteen fields by hand has a real benefit: if BackendUserData ever gains a new field, BackendLoginData gets it automatically, with zero extra edits. Two types that are supposed to be related stay related, instead of slowly drifting apart.
step 3 - types/auth.ts, part two: what your own app promises back
The wire shapes above describe Go honestly - including its quirks (missing status, sometimes-missing error). But you don't want every form in your app dealing with those quirks directly. So this second half of the file defines the app shapes - a cleaned-up, dependable promise your own functions make to the rest of your code.
the base app shape
export type ApiEnvelopeBase = {
success: boolean;
message: string;
error: string | null;
status: number;
};Compare this carefully to BackendEnvelope:
BackendEnvelope (wire) | ApiEnvelopeBase (app) | |
|---|---|---|
error | error?: string - might not exist | error: string | null - always exists, null when there isn't one |
status | doesn't exist at all | status: number - always a real number |
status isn't in Go's JSON body at all - it lives in the HTTP status line (the very first line of any HTTP response, e.g. HTTP/1.1 409 Conflict), which is a separate thing from the JSON body. ApiEnvelopeBase adds it because actions/auth.ts reads it from axios directly and puts it here, so the rest of your app never has to know it came from somewhere else.
the generic constraint: T extends object
type ApiEnvelope<T extends object> = ApiEnvelopeBase & T;extends here is not the class-inheritance extends you might already know - it's a constraint. It means: T can be filled in with anything, as long as that "anything" is some kind of object. Not a bare string, not a number - an object shape.
ApiEnvelope<{ id: string }> // fine - an object
ApiEnvelope<string> // error! string does not satisfy "extends object"Why require this? Because the very next thing this line does is ApiEnvelopeBase & T - merging two object shapes together, the same & mechanic from BackendLoginData above. Merging an object with another object makes sense. Merging an object with a bare string doesn't produce anything usable. The constraint stops that mistake before it can happen.
building every response type from one small piece
export type SignUpResponse = ApiEnvelope<{ id: string }>;
export type LoginResponse = ApiEnvelope<{ user: AuthUser | null }>;
export type ValidateUserResponse = ApiEnvelope<{ user: AuthUser | null }>;
export type VerifyEmailResponse = ApiEnvelopeBase;
export type ResendVerificationResponse = ApiEnvelopeBase;
export type ForgotPasswordResponse = ApiEnvelopeBase;
export type ResetPasswordResponse = ApiEnvelopeBase;
export type LogoutResponse = ApiEnvelopeBase;Each line only writes the extra field that endpoint needs on top of the base four. SignUpResponse expands to { success, message, error, status, id } - five fields, all required. The four endpoints that only ever send a plain message use ApiEnvelopeBase directly, with nothing added.
In plain words:
ApiEnvelopeBaseis "the tidied-up version your own function promises to hand back" - always four fields, always the same shape, no matter what Go actually sent.
step 4 - AuthUser: the shape your React components actually use
export type AuthUser = {
id: string;
firstName: string;
lastName: string;
email: string;
role: string;
avatar?: string;
jobTitle?: string;
active?: boolean;
provider?: string;
createdAt?: string;
updatedAt?: string;
};This is the last shape in the chain, and the friendliest one. Compare it to BackendUserData: first_name becomes firstName, job_title becomes jobTitle - proper camelCase, matching normal JavaScript/TypeScript naming, instead of the snake_case Go sends. This is the shape your components - SignUpForm, UserDropdown, useSession() - actually work with. They never see snake_case at all.
step 5 - mapBackendUser: the translator function
export function mapBackendUser(data: BackendUserData): AuthUser {
return {
id: data.id,
firstName: data.first_name ?? "",
lastName: data.last_name ?? "",
email: data.email ?? "",
role: data.role ?? "USER",
avatar: data.avatar,
jobTitle: data.job_title,
active: data.active,
provider: data.provider,
createdAt: data.created_at,
updatedAt: data.updated_at,
};
}This function does exactly one job: take a BackendUserData (snake_case, mostly-optional, straight from Go) and produce an AuthUser (camelCase, with sensible fallbacks). The ?? operator means "use the value on the left, unless it's missing, then use the value on the right" - so a missing first_name becomes "" instead of undefined, and a missing role becomes "USER" instead of undefined.
Every place in the app that needs a real, friendly user object calls this function first. Nothing else in the app is allowed to read raw BackendUserData directly.
step 6 - actions/auth.ts: where the real call happens
Everything above was description. This file is where the actual work happens.
"use server" - what a Server Action is
"use server"This one line at the top of the file changes everything about how it behaves. Every function exported from a "use server" file becomes a Server Action - a function that Next.js guarantees only ever runs on your server, never in the browser, even when it's called from a "use client" component.
Here's the part that trips people up: when a browser calls a Server Action, it doesn't run the code locally. Next.js secretly sends a network request to your server, runs the real function there, and sends the result back. This is called RPC (Remote Procedure Call) - a function call that looks normal in your code, but is secretly a network round trip. That's exactly why every function in this file wraps its work in try/catch - a network round trip can fail in ways a normal function call never can (timeouts, dropped connections).
baseAPI - the axios instance that actually sends requests
import axios from "axios"
import { env } from "@/lib/env"
const baseAPI = axios.create({
baseURL: env.apiBaseUrl,
headers: {
"Content-Type": "application/json",
"Cache-Control": "no-store, no-cache, must-revalidate",
Pragma: "no-cache",
},
})
export { baseAPI }baseAPI is a pre-configured axios instance - every request made through it automatically starts at env.apiBaseUrl, so the rest of the code only has to write the short path ("/users", "/users/login"), never the full address.
Where does env.apiBaseUrl come from?
API_BASE_URL=http://localhost:8080/api/v1import "server-only"
import { z } from "zod"
const envSchema = z.object({
API_BASE_URL: z.string().url(),
})
const parsed = envSchema.safeParse({
API_BASE_URL: process.env.API_BASE_URL,
})
export const env = {
apiBaseUrl: parsed.success ? parsed.data.API_BASE_URL : "http://localhost:8080/api/v1",
}lib/env.ts reads the raw .env value, checks that it's actually a valid URL using zod, and exports it as env.apiBaseUrl. "server-only" at the top is a safety net - it makes the whole file crash on purpose if anything ever tries to import it into browser code, since this backend address should never ship to the client.
A real bug this exact setup catches: the Go backend in this project groups every route under
/api/v1(router.Group("/api/v1")in Go'smain.go). If.envis missing that/api/v1part, every single request silently 404s - the request reaches the server, but hits no matching route. This is one of the most common early mistakes when wiring a frontend to a Go + Gin backend.
reading the reply - one word, two meanings
This is the single most confusing part for beginners, so let's slow all the way down.
const response = await baseAPI.post<BackendEnvelope<BackendUserData>>("/users", { ...payload })response here is not the JSON Go sent. It's an object axios builds for you, and it wraps the real JSON body inside its own .data field, alongside things like .status:
response
βββ data β the parsed JSON body Go sent (this is a BackendEnvelope)
βββ status β the real HTTP status code, e.g. 201
βββ headers β response headers
And Go's own JSON body - the thing sitting inside response.data - also has a field called data, meaning something completely different: the payload specific to this one endpoint.
{
"success": true,
"message": "Account created!",
"data": { "id": "3f9a1c2e-..." }
}So:
response.data.success // reads the envelope's own field β NOT nested further
response.data.data?.id // reads INSIDE Go's payload β nested one level deepersuccess sits at the top of Go's JSON, right next to message. id sits inside the nested data object. That's the whole reason one line has one .data and the other has two - they're reading from two different depths in the same real JSON.
the try block, field by field
export async function signUpAction(
payload: SignUpPayloadType
): Promise<SignUpResponse> {
try {
const response = await baseAPI.post<BackendEnvelope<BackendUserData>>("/users", {
first_name: payload.firstName,
last_name: payload.lastName,
email: payload.email,
password: payload.password,
confirm_password: payload.confirmPassword,
})
return {
success: response.data.success,
id: response.data.data?.id ?? "",
message: response.data.message,
error: response.data.error ?? null,
status: response.status,
}Notice the object being sent has snake_case keys (first_name, not firstName) - that's the frontend translating its own camelCase form data into the field names Go's JSON binder actually expects.
The function's return type, Promise<SignUpResponse>, is a promise made to whoever calls this function: whatever happens, you will get back exactly these five fields. Every return statement inside this function - in the try block or the catch block - has to satisfy that promise.
the catch block - reading Go's real error, not guessing
} catch (error) {
if (axios.isAxiosError<BackendEnvelope>(error) && error.response) {
return {
success: false,
id: "",
message: error.response.data?.message ?? "Failed To Create Account...!!!π₯Ίπ",
error: error.response.data?.error ?? GENERIC_ERROR,
status: error.response.status,
}
}
console.error(error)
return {
success: false,
id: "",
message: "Failed To Create Account...!!!π₯Ίπ",
error: GENERIC_ERROR,
status: 500,
}
}
}Axios throws an error for any non-2xx HTTP status - a 409 "email already exists" is treated as a thrown error, exactly like a network failure would be. That's why this file needs to tell those two situations apart:
axios.isAxiosError(error) && error.responseis true - Go actually replied, just with an error status.error.responsehas the exact same shape as a successfulresponsewould have - real.data, real.status- so this branch reads Go's actual message and status, instead of guessing.- That check is false - no response ever arrived at all (server down, DNS failure, timeout). There's no real status to report, so the code falls back to a hardcoded
500- not read from anywhere, just chosen to represent "something failed and we don't know Go's real answer."
axios.isAxiosError itself doesn't fetch anything - it's a type guard, a function whose only job is answering "is this really an AxiosError?" so TypeScript will then allow you to safely access .response on it.
Where the status number actually comes from, end to end: Go's controller calls something like
c.JSON(http.StatusConflict, ...). Gin writes409into the real HTTP status line it sends back. Axios parses that status line and exposes it as.status(on success) orerror.response.status(on failure). Your.envfile never enters into this at all - it only decides where the request goes, not what comes back.
step 7 - the supporting files, briefly
These files don't do the heavy lifting, but the two main files depend on all of them.
lib/session.ts - the httpOnly cookie
export async function setSessionCookie(token: string, maxAgeSeconds: number) {
const store = await cookies();
store.set(SESSION_COOKIE, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/",
maxAge: maxAgeSeconds,
});
}After a successful login, loginAction calls this to store the JWT token Go issued, as an httpOnly cookie - meaning browser JavaScript can never read it, only your Next.js server can. maxAgeSeconds comes straight from Go's own expires_in field, so the cookie's lifetime always matches the token's real lifetime - one source of truth, not two numbers that could drift apart.
lib/constants.ts - one shared fallback message
export const GENERIC_ERROR =
"β Error! Something went wrong while processing your request. Please try again or contact support. β οΈ"A small, separate file just for this string. It has to live outside actions/auth.ts because of a strict rule: every export from a "use server" file must be an async function - a plain string constant breaks that rule immediately.
schema/auth.schema.ts - validating the form before it's ever sent
export const SignUpSchema = z.object({
firstName: z.string().min(2).max(50),
password: z.string().min(8).max(100),
confirmPassword: z.string(),
// ...
}).refine((data) => data.password === data.confirmPassword, {
message: "Passwords do not match",
path: ["confirmPassword"],
});
export type SignUpSchemaType = z.infer<typeof SignUpSchema>;zod describes what a valid form submission looks like, and z.infer<typeof SignUpSchema> automatically generates the matching TypeScript type β so the validation rules and the type stay perfectly in sync, with no risk of them disagreeing.
app/layout.tsx - wiring the providers together
<QueryProvider>
<ThemeProvider>
<TooltipProvider>{children}</TooltipProvider>
<Toaster richColors />
</ThemeProvider>
</QueryProvider>QueryProvider here is what makes TanStack Query (and therefore useAuth(), useSession()) work anywhere in the app - every component under it can call useQuery/useMutation safely. Toaster is what actually renders the toast.success(...) / toast.error(...) calls you see throughout the forms.
package.json - what's actually installed
The relevant pieces for this whole system: axios (the HTTP client), zod (schema validation), react-hook-form + @hookform/resolvers (form state, wired to zod), @tanstack/react-query (server-state caching for useAuth/useSession), and sonner (the toast library).
step 8 - the whole journey, start to finish
Here's the complete path a single sign-up click takes, tying every file above into one story:
1. Person fills out SignUpForm, clicks Submit
2. zod (SignUpSchema) validates the form in the browser
3. useAuth()'s signUp() calls handleSignUpService (services/auth.ts)
4. handleSignUpService calls signUpAction (actions/auth.ts) - an RPC hop
5. signUpAction sends a real HTTP POST to Go, via baseAPI (config/axios.ts)
6. Go validates, creates the user, replies with a BackendEnvelope
7. signUpAction reads that reply and rebuilds it as a SignUpResponse
8. That SignUpResponse flows back up: services β hook β form
9. The form checks result.success and shows a toast either way
Every arrow in that list crosses a boundary this guide explained: JSON going over the wire (BackendEnvelope), a Server Action RPC hop ("use server"), and a rebuilt, dependable shape coming back (ApiEnvelopeBase).
run it locally
bun install
bun devIf you ever need to add a missing package (say, axios or zod weren't installed yet):
bun add axios zodAnd if you ever need to run a one-off CLI tool without installing it globally:
bunx <tool-name>common errors and fixes
"Generic type 'BackendEnvelope<T>' requires 1 type argument(s)"
This happens if = never is ever removed from BackendEnvelope<T = never>. Without a default, TypeScript won't let you write the bare BackendEnvelope - every use would need an explicit <...>.
Reading response.data.data.success instead of response.data.success
A very natural mistake - but success sits at the top level of Go's envelope, not inside the nested data payload. Only fields specific to that one endpoint (like id, or the user object) live inside the second .data.
status is undefined even though the type says number
This means something is reading response.data.status instead of response.status. Go never puts status inside its JSON body - it only exists in the HTTP status line, which axios exposes as response.status (success) or error.response.status (failure).
"Only async functions are allowed to be exported in a 'use server' file"
Any "use server" file can only export async functions - not constants, not plain objects. A shared string like GENERIC_ERROR has to live in its own plain file (like lib/constants.ts) and get imported instead.
Every request 404s, even though the backend is running
Check .env's API_BASE_URL against how your Go router is actually grouped. If Go registers routes under router.Group("/api/v1"), then API_BASE_URL must end in /api/v1 too - otherwise every request lands on a path Go never registered.
quick reference
| Type | What it describes |
|---|---|
BackendEnvelope<T> | The raw envelope Go actually sends |
BackendUserData | Go's raw, snake_case user fields |
BackendLoginData | BackendUserData + a login token |
ApiEnvelopeBase | The tidied-up envelope your app promises back |
ApiEnvelope<T> | ApiEnvelopeBase + one extra endpoint-specific field |
AuthUser | The friendly, camelCase shape components use |
mapBackendUser() | Turns BackendUserData into AuthUser |
final checklist
- Understand that
types/auth.tsonly describes shapes - it never runs - Understand that
actions/auth.tsdoes the real work - one real network call per function - Know the difference between
response.data(axios's wrapper) andresponse.data.data(Go's nested payload) - Know that
statusalways comes from the HTTP status line, never from the JSON body - Know why
"use server"files can only export async functions - Confirm
.env'sAPI_BASE_URLmatches your Go router's actual path prefix
conclusion
The clean mental model for this whole system:
types/auth.ts β describes every shape, on both sides of the wire
actions/auth.ts β does the real talking, and always hands back
the same, predictable shape - success or failure
Once you can read BackendEnvelope<BackendUserData> and immediately know "this describes Go's raw reply, including its data payload," and you can read Promise<SignUpResponse> and immediately know "this function promises exactly these five fields, no matter what," the rest of the codebase becomes much easier to follow - every other action file in this project follows this exact same pattern.
resources
- TypeScript Handbook - Generics
- TypeScript Handbook - Intersection Types
- Axios documentation
- Next.js - Server Actions and Mutations
- Gin web framework documentation
- MDN - HTTP response status codes