Next.js developer in Timișoara

Next.js developer for Timișoara companies. One topic in depth: sending invoices to the ANAF RO e-Factura API from a Next.js application, from ANAF's own documentation.

Next.js developer

My place in the WordPress community

  • I have had a wordpress.org account since 2006.
  • I contributed to WordPress core for versions 7.0 and 7.1.
  • I maintain 30 plugins on wordpress.org.
  • I organise and speak at WordCamps.
  • I have attended every WordCamp Europe from 2017 to 2026.

My WordPress.org profile

I am Mariusz Szatkowski, one developer in Gdynia, Poland, building Next.js applications from layouts that my clients supply. This page covers one integration that Romanian companies ask for: sending invoices to the ANAF RO e-Factura system from a Next.js application. It follows ANAF's own documents, and it says where the work sits in a Next.js codebase.

#What the Ministry requires, and since when

The Ministry of Finance states on its e-Factura home page the dates from which sending in the system became mandatory:

  • reporting of B2B invoices from 1 January 2024;
  • B2B invoicing through the system from 1 July 2024;
  • reporting in the B2C relationship from 1 January 2025.

For B2C, the technical information page adds that the new upload URL for B2C is mandatory from 31 March 2025, and that the test platform accepts a technical identifier made of thirteen zeros in place of a CNP. A Next.js shop that sells to consumers and to companies therefore calls two different upload routes.

Victory Square in Timișoara

Photo: Chainwit., CC BY 4.0, Wikimedia Commons.

#Two ways to authenticate

The Ministry’s API presentation lists every call twice. One variant presents a digital certificate at the moment of the call, on webserviceapl.anaf.ro. The other uses OAuth 2.0, on api.anaf.ro. For a web application, OAuth is the route that fits, because no browser certificate has to be presented on each server call.

ANAF’s OAuth document explains who stands behind the token. The identity provider, logincert.anaf.ro, authenticates the user with a qualified digital certificate of a person registered in ANAF’s online portal with one of the SPV PJ rights: legal representative, designated representative or authorised person. The protected service, api.anaf.ro, accepts calls with the token.

Two consequences matter for a project:

  1. The token identifies the certificate holder, not the application. ANAF writes that both tokens are generated for the digital certificate. The application has a client ID, but the user is identified by the certificate serial.
  2. Someone with the certificate must act at set times. The access token is a JWT valid for 90 days and the refresh token for 365 days. A refresh call returns a new pair and both values must be saved. When the refresh token expires, the certificate holder logs in again through the authorisation step. I put that date in the handover document and in the report, because it is a yearly task that is easy to forget.

ANAF also states that securing the tokens is the developer’s responsibility. If tokens are compromised, they must be sent to ANAF so that access with them is blocked.

#Registering the application and getting the first token

The OAuth document describes the steps in the ANAF portal. A developer registers under the section for application developers, logs in, opens the OAuth profile editor, names the application, selects the e-Factura service, enters the callback URL and generates a client ID. The portal then shows the grant type, callback URL, authorisation URL, client ID and client secret.

The grant type is the authorisation code. The authorisation endpoint is https://logincert.anaf.ro/anaf-oauth2/v1/authorize and the token endpoint is https://logincert.anaf.ro/anaf-oauth2/v1/token. The client authenticates with HTTP Basic. The document also requires a parameter token_content_type=jwt, sent in the query of the authorisation request and in the body of the token request. The document gives 60 seconds as the interval for obtaining a valid token, after which the connection resets.

Whose certificate, whose company, and whose client ID? Settle this with your accountant before I start. The registration is made by a person with the rights, and I cannot do it for you.

#The four calls an invoice goes through

The API presentation, which the Ministry’s page lists as updated on 13 February 2025, describes the flow:

CallWhat it doesNotes from ANAF
uploadSends the invoice XMLQuery parameters standard (UBL, CN, CII or RASP) and cif; optional extern, autofactura, executare; B2C has its own uploadb2c
stareMesajStatus of an uploadTakes the upload index returned by upload; answers ok, nok or in processing
listaMesajeFacturaLists messages ready to downloadzile from 1 to 60, cif, optional filter E, T, P or R; a paginated variant takes start and end time
descarcareDownloads an answerTakes the message id from the list; returns a zip with two XML files

CN is a credit note and RASP is a message from the buyer to the issuer. The status ok means the file was validated and processed, and the invoice is then available to the buyer. The status nok means errors were found, and in that case the invoice does not reach the buyer. The zip from descarcare holds the original invoice, or the errors, and a file with the Ministry’s electronic signature.

Two helper services help before the upload. validare checks an XML against the standard, FACT1 or FCN, with a plain text content type. A separate call converts the XML to PDF, and ANAF warns that for an unvalidated XML it cannot guarantee that the PDF is correct.

#Where the code lives in a Next.js application

The Next.js documentation draws the line that this integration needs. Environment variables without the NEXT_PUBLIC_ prefix are available only in the Node.js environment, and ones with the prefix are inlined into the JavaScript bundle at build time. The data security guide recommends marking server modules with the server-only package, so that an import from client code fails the build.

So the ANAF module is server code, and the secret never reaches the browser:

// lib/anaf.ts
import 'server-only'

const TOKEN_URL = 'https://logincert.anaf.ro/anaf-oauth2/v1/token'
const API = 'https://api.anaf.ro/test/FCTEL/rest' // change test to prod at go-live

export async function refreshTokens(refreshToken: string) {
  const basic = Buffer.from(
    `${process.env.ANAF_CLIENT_ID}:${process.env.ANAF_CLIENT_SECRET}`,
  ).toString('base64')
  const res = await fetch(TOKEN_URL, {
    method: 'POST',
    headers: {
      Authorization: `Basic ${basic}`,
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: new URLSearchParams({
      grant_type: 'refresh_token',
      refresh_token: refreshToken,
    }),
  })
  if (!res.ok) throw new Error(`ANAF token refresh failed: ${res.status}`)
  return (await res.json()) as { access_token: string; refresh_token: string }
}

export async function uploadInvoice(xml: string, cif: string, accessToken: string) {
  const url = `${API}/upload?standard=UBL&cif=${encodeURIComponent(cif)}`
  const res = await fetch(url, {
    method: 'POST',
    headers: { Authorization: `Bearer ${accessToken}` },
    body: xml,
  })
  if (res.status === 429) throw new Error('ANAF rate limit reached')
  return res.text()
}

A route handler in the App Router calls uploadInvoice after the invoice is saved. Three decisions around it matter more than the fetch itself:

  • The refresh token lives in a database row, not in an environment variable. Each refresh returns a new pair and ANAF says to save both, so a value fixed at deploy time goes stale.
  • The upload is a queued job, not part of the checkout request. ANAF processes the file after the call, so the shop stores the upload index and checks the result later.
  • The invoice state is a field in your data: created, uploaded, ok, nok. The accountant sees it, and a nok sends the errors back to the person who issued the invoice.

#The limits that shape the design

ANAF publishes the limits in a text file linked from its technical page. The whole API allows 1000 calls per minute, and a call over the limit returns status 429. Per method, the file states:

  • upload: up to 1000 RASP files per day per CUI, with no limit on invoice files;
  • status: up to 100 queries per day for one message;
  • list: up to 1500 queries per day per CUI for the simple list, and up to 100,000 for the paginated one;
  • descarcare: up to 10 downloads per day for one message.

The file adds that the limits can change, that you can write to ANAF for a review, and that repeatedly ignoring the limit messages can lead to blocked access for the user and, in serious cases, for the application. A tight polling loop on status is therefore a design error. I poll on a schedule, use the paginated list for bulk checks, and download each message once and store it.

#How a project runs with me

  • Written brief: the company, the invoice types, B2B, B2C or both, and where invoices are created today.
  • Written scope and assumptions: which calls, which environments, who owns the certificate and the client ID.
  • Test environment first: the whole flow runs against the test URLs and your accountant reviews the results.
  • Acceptance: an invoice that ends in ok, an invoice that ends in nok with the errors visible, a refresh of the tokens, and a rate limit answer handled.
  • Handover: the token expiry date, the list of environment variables, and the runbook for the yearly re-authorisation.

I design the layout and wireframes, or take your own design. I implement the screens that show invoice states from the approved layout. I work remotely and in writing, with no meetings or calls.

#A checklist you can use without hiring me

QuestionA good answer
Who holds the certificate with SPV PJ rights?A named person, who knows the yearly step
Where is the refresh token stored?In a database, encrypted, replaced on each refresh
Does any ANAF call run in the browser?No
Are uploads queued?Yes, with the upload index stored
How is status checked?On a schedule within the daily limits
What happens on nok?The errors reach the person who issued the invoice
Has the test environment been used end to end?Yes, before the production URL

#What I need from you

  • The invoice types and the systems that create invoices today.
  • A named owner of the certificate and a decision on who registers the application.
  • Your accountant’s rules for numbering, credit notes and corrections.
  • The layout for any screens that show invoice states.

#Questions Timișoara companies ask

#Can the browser call the ANAF API directly?

It should not. The tokens belong to a certificate holder and ANAF puts the responsibility for storing them securely on the developer. In Next.js the calls run on the server, and variables without the NEXT_PUBLIC_ prefix stay off the browser.

#How often does someone have to log in again?

ANAF issues the access token for 90 days and the refresh token for 365 days. A refresh call returns a new access token and a new refresh token, and both must be saved. When the refresh token expires, the certificate holder authorises the application again.

#What does an invoice with status nok mean?

The file was not processed and the invoice does not reach the buyer. ANAF lets you download the answer with the errors and its signature, so the application can show them to the person who issued the invoice.

#Why not poll the status in a loop?

ANAF allows at most 100 status queries per day for one message, and 1500 simple list queries per day for one CUI. Repeated disregard of the limit messages can lead to blocked access.

#Is there a test environment?

Yes. The documented URLs exist for test and for production, for both the certificate and the OAuth routes. I build and accept against the test environment before the production URL is switched on.

#Do you write the invoice XML too?

Yes, as a generator in the application, validated against the ANAF validation service before upload. The invoice data, tax rules and accounting decisions stay with you and your accountant. For other Next.js work, see the Next.js developer service page.

#Write to me

Send me what you invoice, to whom, and from which system, plus your deadline. I reply in writing with questions and then a written estimate with scope and assumptions. The first estimate is free. I reply within 24 hours on working days (CET). Use the contact page.

Need this service: Next.js developer in Timișoara?

Describe your project by e-mail. I reply within 24 hours.

Describe your project