Next.js developer in Wrocław

Next.js for businesses in Wrocław, delivered remotely by one developer.

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.
  • Local WordPress meetup: WordPress Wrocław

My WordPress.org profile

A Next.js app that sells to Polish businesses has to deliver its invoices through KSeF, the National e-Invoice System (Krajowy System e-Faktur), and every step of that belongs in server code. I am Mariusz Szatkowski, a Gdynia developer who has built with WordPress since 2006 and works remotely and in writing. For a Wroclaw company whose shop, SaaS billing or client portal runs on Next.js, this page lays out what the Ministry of Finance publishes about the KSeF API 2.0 and how the pieces map onto a Next.js server. Which invoices you must issue, and when, is for you and your accountant to confirm.

Centennial Hall in Wroclaw

Centennial Hall (Hala Stulecia) in Wroclaw. Photo by Jar.ciurus, licensed CC BY-SA 3.0 pl, found on Wikimedia Commons.

#When did KSeF become mandatory?

The Ministry of Finance page on the KSeF start dates, last modified on 30 April 2026, gives them in these words (my translation):

  • from 1 February 2026 for companies whose sales in 2024 exceeded PLN 200 million (including VAT)
  • from 1 April 2026 for the others
  • until 31 December 2026 invoices may still be issued outside KSeF, on paper or electronically, if the VAT-inclusive sales on such invoices in a given month do not exceed PLN 10,000

The ministry roadmap lists the next step: from 1 January 2027 KSeF 2.0 becomes mandatory for the businesses exempted so far, those with up to PLN 10,000 a month. The same roadmap says KSeF 2.0 has been available since 1 February 2026 for large companies and for receiving invoices.

The legal basis is the VAT act. In the consolidated text published as Dz.U. 2026 item 1263, article 106ga(1) says taxpayers are obliged to issue structured invoices using KSeF. Article 106ga(2) lists exceptions, among them invoices to individuals who do not run a business. Article 106na(3) adds a date a developer has to model: a structured invoice counts as received through KSeF on the day KSeF assigns its identifying number.

#Why does KSeF code belong on the server?

The KSeF API authenticates a company acting in a tax context, such as a NIP. The login uses a KSeF token or a qualified signature or KSeF certificate, and the response is a pair of tokens that the ministry documentation says must be treated as confidential and stored securely. None of this can reach client code.

The Next.js documentation gives the tools for that boundary:

  • Route Handlers create request handlers for a route with the Web Request and Response APIs, so a POST from the checkout can trigger invoicing on the server
  • environment variables without the NEXT_PUBLIC_ prefix are available only in the Node.js environment and never reach the browser
  • import 'server-only' in a module causes a build error if a client component imports it, which protects the KSeF client from being bundled by mistake
  • the runtime route option defaults to 'nodejs', and the documentation marks the Edge Runtime as deprecated, so the KSeF code runs in Node.js with its full crypto library

The ministry publishes official client libraries for .NET and Java only. A Next.js app either talks to the REST API directly, as in the samples below, or calls a separate service built on one of those libraries.

#Which KSeF environments exist?

The ministry integrator page lists three environments for KSeF API 2.0:

EnvironmentAPI baseWhat it is for
Test (integration)https://api-test.ksef.mf.gov.pl/v2anonymised data; invoices have no legal effect and are deleted after some time
Demo (pre-production)https://api-demo.ksef.mf.gov.pl/v2real authentication data and real permissions; invoices have no legal effect
Productionhttps://api.ksef.mf.gov.pl/v2real permissions; invoices have legal effect

Each environment publishes its contract as an OpenAPI 3.0.4 file and an interactive documentation page. The API documentation was first presented on 30 June 2025, and the changelog lives in the ministry GitHub repository CIRFMF/ksef-api. The integrator guide in CIRFMF/ksef-docs describes each scenario step by step. The ministry also takes requests to raise API limits in Demo and production, if a real operational need justifies it.

In a Next.js project the base URL is an environment variable per deployment, so preview builds point at the test environment and only the production deployment can issue invoices with legal effect.

#How does authentication work?

The integrator guide describes this flow:

  1. POST /auth/challenge returns a challenge and a timestamp, including timestampMs. A challenge lives for 10 minutes.
  2. The company proves its identity in one of two ways: a signed XML document AuthTokenRequest in XAdES format sent to POST /auth/xades-signature, or a KSeF token sent to POST /auth/ksef-token.
  3. For the token route, the string token|timestampMs is encrypted with RSA-OAEP, SHA-256 and MGF1, using the ministry public key, and Base64-encoded. The request also names the context, for example a NIP.
  4. The response carries an authenticationToken and a referenceNumber. GET /auth/{referenceNumber} with that bearer token reports the status.
  5. POST /auth/token/redeem returns an accessToken (a JWT with a short lifetime set in its exp field) and a refreshToken valid for up to 7 days. Redeem works once; a second call with the same token returns error 400.
  6. POST /auth/token/refresh with the refresh token returns a new access token without a new login.

The ministry public keys come from GET /security/public-key-certificates. Each entry is a DER certificate in Base64 with a usage, either KsefTokenEncryption or SymmetricKeyEncryption, and validity dates. The code selects the certificate by usage and validity date at runtime, so a key rotation needs no deploy.

On tokens versus certificates, the ministry KSeF certificate page says tokens will be kept without an end date and the regulation will be amended accordingly. It also stresses that they are not equivalent: a token carries the permissions declared when it was generated, while a KSeF certificate is only a means of authentication. A certificate is valid for no longer than 2 years.

A shortened Route Handler that requests a challenge and sends the encrypted token:

// app/api/ksef/auth/route.ts
import 'server-only'
import { X509Certificate, publicEncrypt, constants } from 'node:crypto'

const BASE = process.env.KSEF_API_BASE!
const json = (body: unknown) => ({
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify(body),
})

async function ksefPublicKey(usage: string) {
  const certs = await fetch(`${BASE}/security/public-key-certificates`).then((r) => r.json())
  const now = Date.now()
  const cert = certs.find(
    (c: any) => c.usage.includes(usage) && Date.parse(c.validFrom) <= now && now < Date.parse(c.validTo),
  )
  return new X509Certificate(Buffer.from(cert.certificate, 'base64')).publicKey
}

export async function POST() {
  const challenge = await fetch(`${BASE}/auth/challenge`, { method: 'POST' }).then((r) => r.json())
  const key = await ksefPublicKey('KsefTokenEncryption')
  const encryptedToken = publicEncrypt(
    { key, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
    Buffer.from(`${process.env.KSEF_TOKEN}|${challenge.timestampMs}`),
  ).toString('base64')

  const init = await fetch(`${BASE}/auth/ksef-token`, json({
    challenge: challenge.challenge,
    contextIdentifier: { type: 'Nip', value: process.env.KSEF_NIP },
    encryptedToken,
  })).then((r) => r.json())

  // Next: poll GET /auth/{referenceNumber}, then POST /auth/token/redeem once.
  return Response.json({ referenceNumber: init.referenceNumber })
}

In production the route would not be public: the invoicing job calls the same server function, and the tokens go to an encrypted store, never into a response.

#How is an invoice sent?

An interactive session sends single invoices. The guide lists what comes first: a 256-bit symmetric key and a 128-bit initialisation vector, the invoice encrypted with AES-256-CBC and PKCS#7 padding, and the symmetric key encrypted with RSAES-OAEP (SHA-256, MGF1) under the ministry public key for SymmetricKeyEncryption.

  1. POST /sessions/online opens the session with a form code and the encrypted key. For the FA(3) structure the form code is system code FA (3), schema version 1-0E, value FA. Several sessions can stay open under one authentication.
  2. POST /sessions/online/{referenceNumber}/invoices sends one invoice with five required fields: the SHA-256 hash of the original XML and its size, the SHA-256 hash of the encrypted file and its size, and the encrypted content in Base64. An optional offlineMode flag declares an invoice issued offline.
  3. Verification runs asynchronously after the upload.
  4. POST /sessions/online/{referenceNumber}/close closes the session and starts generating a collective UPO, the official confirmation of receipt.
import { randomBytes, createCipheriv, createHash, publicEncrypt, constants, type KeyObject } from 'node:crypto'

const sha256 = (b: Buffer) => createHash('sha256').update(b).digest('base64')

export function encryptInvoice(xml: Buffer, key: Buffer, iv: Buffer) {
  const cipher = createCipheriv('aes-256-cbc', key, iv)
  const encrypted = Buffer.concat([cipher.update(xml), cipher.final()])
  return {
    invoiceHash: sha256(xml),
    invoiceSize: xml.length,
    encryptedInvoiceHash: sha256(encrypted),
    encryptedInvoiceSize: encrypted.length,
    encryptedInvoiceContent: encrypted.toString('base64'),
  }
}

export function sessionEncryption(publicKey: KeyObject) {
  const key = randomBytes(32)
  const iv = randomBytes(16)
  const encryptedSymmetricKey = publicEncrypt(
    { key: publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256' },
    key,
  ).toString('base64')
  return { key, iv, encryption: { encryptedSymmetricKey, initializationVector: iv.toString('base64') } }
}

Verification after upload runs asynchronously and the UPO comes after the session closes, so a checkout request should not wait for them. The order gets an invoice record with a state, and a server job moves it from queued to sent, accepted or rejected.

#What is the KSeF number?

The ministry page on KSeF numbers says KSeF assigns a unique number automatically after it accepts the invoice. The number is returned in the UPO and is not part of the XML file. It is also not the invoice number from field P_2, which the seller assigns in its own series. The invoice record therefore needs both: the seller’s number, set before sending, and the KSeF number, filled in when the UPO arrives.

For the issue date, the ministry page on offline24 says the date the taxpayer enters in field P_1 is the issue date, and that the same rule applies to an online invoice that reaches KSeF later than that date. Your accountant should confirm how your invoices are dated, and the record should keep P_1, the sending time and the KSeF number apart.

#When does the invoice need a QR code?

Article 106gb(4) of the VAT act lists buyers who get the invoice in a way agreed with them instead of through KSeF, among them buyers without a Polish seat or fixed establishment, buyers without a tax number, and consumers. Article 106gb(5) obliges the taxpayer to mark the invoice with a verification code when it is shared with such a buyer outside KSeF, or used outside KSeF.

The ministry QR page and the integrator guide describe the two codes:

  • KOD I gives access to the invoice in KSeF. It is a link built from the QR address of the environment, the seller NIP, the issue date from field P_1 in DD-MM-YYYY format and the SHA-256 hash of the invoice file in Base64URL. In production the address is https://qr.ksef.mf.gov.pl/invoice. Under the code goes the KSeF number, or the word OFFLINE for an invoice not yet in KSeF.
  • KOD II confirms the issuer for offline invoices handed over before they reach KSeF. It carries the label CERTYFIKAT and needs a KSeF certificate of type 2 (offline).

The guide example for the test environment, seller NIP 1111111111, issued on 1 February 2026, is https://qr-test.ksef.mf.gov.pl/invoice/1111111111/01-02-2026/UtQp9Gpc51y-u3xApZjIjgkpZ01js-J8KflSPW8WzIE. In Next.js the link can be built in the same server module that renders the PDF or email:

import { createHash } from 'node:crypto'

// p1 is the issue date from field P_1 of the invoice, as YYYY-MM-DD
export function ksefInvoiceLink(qrBase: string, nip: string, p1: string, xml: Buffer) {
  const [yyyy, mm, dd] = p1.split('-')
  const date = `${dd}-${mm}-${yyyy}`
  const hash = createHash('sha256').update(xml).digest('base64url')
  return `${qrBase}/invoice/${nip}/${date}/${hash}`
}

For a consumer order this matters even though article 106ga(2) exempts invoices to individuals from the KSeF duty: the ministry states such invoices may be issued in KSeF voluntarily, and once they are, the QR rules apply when the invoice is handed over.

#What happens when KSeF is unreachable?

The ministry describes three special procedures that run as one technical offline mode: offline24 (article 106nda, for example when the connection fails or by the issuer’s choice), offline during KSeF unavailability (article 106nh) and the failure mode (article 106nf). For offline24 the rules are:

  • the invoice uses the current structure, FA(3) since 1 February 2026, and is issued electronically
  • it is sent to KSeF without delay, no later than the next business day after issue
  • if KSeF announces a failure in the meantime, the invoice goes in within 7 business days after the failure ends
  • if a total failure is announced in the media, the invoice is not sent later
  • handed to a buyer outside KSeF before sending, it carries both QR codes, which needs the type 2 certificate

In the app this is the same queue with a deadline per invoice. A job that has not reached the accepted state by the end of the next business day raises an alert to a person.

#Checklist for a Wroclaw Next.js app

  • Keep all KSeF calls in server-only modules and Route Handlers.
  • Store the KSeF token, NIP and API base as server environment variables per deployment.
  • Test against the test environment, then Demo with real permissions, before production.
  • Fetch ministry public keys by usage and validity date.
  • Store access and refresh tokens encrypted, and refresh before expiry.
  • Give each invoice a state, the seller number, the KSeF number and the UPO.
  • Build KOD I links for invoices shared outside KSeF, and plan the type 2 certificate if offline24 is used.
  • Alert on invoices still unsent at the end of the next business day.
  • Note 1 January 2027 if you have relied on the PLN 10,000 relief.

#How does a project run?

  1. You send me the repository, how invoices are produced today, your KSeF access (token or certificate) for the test environment, and the deadline. My first email back to you arrives within 24 hours on working days.
  2. I write down the scope, assumptions and questions about invoice types and buyers.
  3. I build against the test environment, then you run the same flow in Demo with your real permissions.
  4. You approve in writing, and production follows.

I am not a tax adviser, so the classification of each sale stays with your accountant. More about my Next.js work is on the Next.js developer page.

#Send me your invoicing flow

If your Wroclaw team runs sales or billing in Next.js and needs KSeF, describe the current invoice flow, the buyers you invoice and your deadline on the contact page. Your first written estimate for the KSeF work is free, and test access to KSeF, if you already have it, shortens the first reply.

Need this service: Next.js developer in Wrocław?

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

Describe your project

Explore other WordPress services and knowledge base