Supabase Printing: Send PDFs to Local Printers by API

Connect Supabase to physical printers using an authenticated Edge Function and PrintScaler. Keep PDFs private, enforce printer permissions, and retry requests without duplicate output.

By the PrintScaler team · · 9 min read

Private cloud document storage connected through a server function to a local computer and printer.

Supabase printing works by sending an authenticated request from an Edge Function to a printing service that can reach your physical printer. With PrintScaler, your function submits a PDF through HTTPS, and a local agent delivers it to the selected printer—without a browser print dialog or an inbound connection to your office network. This guide builds that workflow using Supabase Auth, private Storage, and server-controlled printer routing.

How Supabase connects to a local printer

A Supabase Edge Function runs in the cloud. It cannot directly access a USB printer attached to a warehouse computer, and a private network address such as 192.168.1.50 does not identify a reachable printer from that cloud environment.

Instead, separate document preparation from physical delivery:

  1. Your application generates a PDF and saves it in private Supabase Storage.
  2. Your trusted backend creates a print-request record identifying the document, its owner, and its destination printer.
  3. An authenticated user invokes an Edge Function with that request’s ID.
  4. The function checks access, downloads the PDF, and submits it to PrintScaler.
  5. The PrintScaler agent delivers the job to the local printer.

The agent uses an outbound WebSocket connection, so this setup does not require opening inbound firewall ports.

This architecture suits packing slips, invoices, work orders, and other PDFs generated by a Supabase-backed application. If you are deploying on a different serverless platform, the related AWS Lambda printing guide covers that environment separately.

Choose where each part of the workflow belongs

The most important security decision is to keep printer selection and printing credentials out of browser-controlled input.

Component Responsibility Must not do
Browser or mobile application Request an authorized print operation Supply an unrestricted printer ID or PrintScaler key
Supabase database Store ownership and approved routing Let users rewrite destination printers arbitrarily
Private Storage bucket Hold the printable PDF Expose documents publicly just to make printing easier
Edge Function Authenticate, authorize, and submit Treat possession of a request UUID as authorization
PrintScaler agent Connect the local printer to the service Require a publicly exposed printer port

In the example below, each database row represents one intended print operation, not merely one document. Retrying that operation reuses its ID. An intentional second copy requires a new, authorized operation.

Step 1: Connect and test the physical printer

On a Windows, macOS, Linux, or Raspberry Pi computer that can already print locally:

  1. Install the printer and its appropriate driver.
  2. Print a local test document to confirm the operating system can reach it.
  3. Install the PrintScaler agent.
  4. Enter the pairing code in the PrintScaler dashboard to link the computer.
  5. Find the printer in the dashboard and use its test-page button.
  6. Record the printer ID for your application’s routing configuration.

For an initial test, use an ordinary PDF printer workflow rather than introducing label-language commands or custom receipt formatting at the same time.

The agent starts automatically after reboots and reports printers and their status. Nevertheless, the host computer must be running and the printer must be available for immediate output.

For a multi-tenant application, your trusted backend should map each tenant, site, or workstation to its approved printer. Never assume that an authenticated user may print to every printer your API key can access.

Step 2: Create a private PDF bucket and request table

Create a private Supabase Storage bucket named print-pdfs. For this example, store files under an owner-specific prefix:

<user-uuid>/packing-slip-10482.pdf

Then create a small table for approved print operations:

create table public.print_requests (
  id uuid primary key default gen_random_uuid(),
  owner_id uuid not null references auth.users(id),
  storage_path text not null,
  printer_id bigint not null,
  created_at timestamptz not null default now()
);

alter table public.print_requests enable row level security;

create policy "Owners can read their print requests"
  on public.print_requests
  for select
  to authenticated
  using ((select auth.uid()) = owner_id);

Add a Storage read policy for the private bucket:

create policy "Owners can read their printable PDFs"
  on storage.objects
  for select
  to authenticated
  using (
    bucket_id = 'print-pdfs'
    and (storage.foldername(name))[1] =
      (select auth.uid())::text
  );

These policies deliberately grant only read access. Provision the PDFs and request rows through a trusted backend that checks the business operation, assigns the correct owner, and selects an approved printer. Keep any service-role credential used for that provisioning server-side.

Audit existing policies too: an older, broader policy can undermine the restrictions shown here. Also verify the necessary table privileges for the authenticated role in your project; RLS policies do not replace SQL grants.

For shared warehouse documents, replace the owner-only model with your organization’s membership rules. Both the request row and the stored file must follow the same authorization model.

Step 3: Store the PrintScaler key as a function secret

Set a server-side secret for the Edge Function:

supabase secrets set PRINTSCALER_API_KEY=psk_your_key_here
supabase secrets set APP_ORIGIN=https://app.example.com

Replace the example origin with your application’s exact origin. Do not put the PrintScaler key in frontend environment variables or a client-side JavaScript bundle.

The function below also uses Supabase’s standard SUPABASE_URL and SUPABASE_ANON_KEY environment variables. It passes the caller’s authorization header into the Supabase client, so database and Storage reads run under that user’s permissions.

The anonymous project key is not a substitute for the user’s access token. Authentication comes from the signed-in user’s bearer token, and authorization comes from the applicable policies and trusted routing data.

Step 4: Build the Supabase printing Edge Function

Create the function:

supabase functions new print-document

Replace its index.ts with the following implementation:

import { createClient } from 'npm:@supabase/supabase-js@2';

const corsHeaders = {
  'Access-Control-Allow-Origin': Deno.env.get('APP_ORIGIN')!,
  'Access-Control-Allow-Headers':
    'authorization, x-client-info, apikey, content-type',
  'Access-Control-Allow-Methods': 'POST, OPTIONS',
};

function reply(status: number, body: unknown) {
  return new Response(JSON.stringify(body), {
    status,
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  });
}

function toBase64(bytes: Uint8Array): string {
  let binary = '';
  for (let i = 0; i < bytes.length; i += 32768) {
    binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
  }
  return btoa(binary);
}

Deno.serve(async (req) => {
  if (req.method === 'OPTIONS') {
    return new Response(null, { headers: corsHeaders });
  }
  if (req.method !== 'POST') {
    return reply(405, { error: 'Method not allowed' });
  }

  const authorization = req.headers.get('Authorization');
  if (!authorization) return reply(401, { error: 'Sign in first' });

  const supabase = createClient(
    Deno.env.get('SUPABASE_URL')!,
    Deno.env.get('SUPABASE_ANON_KEY')!,
    { global: { headers: { Authorization: authorization } } },
  );

  const { data: auth, error: authError } = await supabase.auth.getUser();
  if (authError || !auth.user) {
    return reply(401, { error: 'Invalid session' });
  }

  const body = await req.json().catch(() => null);
  if (!body || typeof body.requestId !== 'string') {
    return reply(400, { error: 'requestId is required' });
  }

  const { data: job, error: lookupError } = await supabase
    .from('print_requests')
    .select('id, printer_id, storage_path')
    .eq('id', body.requestId)
    .single();

  if (lookupError || !job) {
    return reply(404, { error: 'Print request unavailable' });
  }

  const { data: pdf, error: downloadError } = await supabase.storage
    .from('print-pdfs')
    .download(job.storage_path);

  if (downloadError || !pdf) {
    return reply(409, { error: 'PDF unavailable' });
  }

  // Application-specific limit, not a PrintScaler service limit.
  if (pdf.size > 5 * 1024 * 1024) {
    return reply(413, { error: 'PDF exceeds this function’s size limit' });
  }

  try {
    const result = await fetch(
      'https://api.printscaler.com/v1/printjobs',
      {
        method: 'POST',
        headers: {
          Authorization: `Bearer ${Deno.env.get('PRINTSCALER_API_KEY')!}`,
          'Content-Type': 'application/json',
          'X-Idempotency-Key': `supabase-print:${job.id}`,
        },
        body: JSON.stringify({
          printerId: job.printer_id,
          contentType: 'pdf_base64',
          content: toBase64(new Uint8Array(await pdf.arrayBuffer())),
          title: `Print request ${job.id}`,
        }),
      },
    );

    if (!result.ok) {
      console.error('Print submission rejected', result.status, job.id);
      return reply(502, { error: 'Print submission was not confirmed' });
    }

    return reply(202, { accepted: true, requestId: job.id });
  } catch {
    return reply(502, { error: 'Print submission was not confirmed' });
  }
});

Deploy it:

supabase functions deploy print-document

This example uses PrintScaler’s supported pdf_base64 content type. It avoids giving a third party a publicly accessible document URL and avoids a signed download link expiring while a printer computer is offline.

Base64 increases payload size and memory usage. The five-megabyte check is a conservative limit chosen for this example, not a published PrintScaler limit. Evaluate your Edge Function runtime limits and expected document sizes before production use.

The PrintScaler print-job reference documents the request endpoint and supported content types.

Step 5: Call the function from your application

Once your trusted backend has created the print-request row, invoke the function using your signed-in Supabase client:

const { data, error } = await supabase.functions.invoke(
  'print-document',
  { body: { requestId: approvedPrintRequestId } },
);

if (error) {
  showPrintError('Submission not confirmed. Retry the same request.');
} else if (data.accepted) {
  showPrintStatus('Submitted to the printing service');
}

Notice what the browser does not send: a PDF URL, printer ID, owner ID, or printing API key. Those values come from authenticated server-side lookups.

Disable the button while the request is pending to improve the user experience, but do not treat a disabled button as duplicate protection. Users can reload pages, retry after timeouts, or submit from two tabs.

CORS also is not authorization. The allowed origin controls browser access to responses; the user-token validation and RLS policies are what protect the operation.

Make retries safe and intentional reprints explicit

A network failure creates an ambiguous result: the print service may have accepted the request even if your function never received its response.

The example addresses this with:

X-Idempotency-Key: supabase-print:<print-request-uuid>

Every retry of the same intended operation uses the same key. Do not generate a new UUID inside the Edge Function each time it runs, because that would turn retries into distinct print submissions.

Keep each request’s document and destination immutable after creation. If a user chooses “Print another copy,” have your trusted backend authorize that action and create a new request row. Record the reason and actor if your workflow needs an audit trail.

For automated retries, distinguish temporary problems from permanent ones. Back off on rate-limit responses and transient network errors; do not repeatedly retry a document the user cannot access. PrintScaler’s API rate limit is 10 requests per second, with a burst of 30, so larger workflows need controlled dispatch rather than unrestricted parallel calls.

See the guide to preventing duplicate print jobs for a deeper explanation of retry boundaries.

Track printing separately from submission

The function’s 202 response means the printing request was accepted. It does not mean paper has emerged from the printer.

PrintScaler exposes states including new, sent_to_client, queued, in_progress, done, error, cancelled, and expired. Use those states to distinguish submission, processing, and reported completion. A reported completion should not be treated as independent proof that someone collected or inspected the paper.

For production, persist the returned print-job identifier according to the documented response format and correlate subsequent events with your application request. The minimal function above does not yet persist that response or maintain a status dashboard.

Signed print-job webhooks can update your application’s status records. Verify the HMAC-SHA256 signature before trusting an event, and handle retries without applying the same update twice.

If the agent computer goes offline, jobs can queue until it reconnects, subject to their configured expiry. Set expiry to match the business task: an old warehouse packing slip may still be useful, while an outdated time-sensitive ticket may not be.

Test these failure cases before launch

Test more than a successful print:

  • Another user’s request ID: the function should not retrieve the row or print its document.
  • An unauthorized Storage path: the file download should fail even if the request lookup succeeds.
  • A double-click or client retry: the same request ID should retain the same idempotency key.
  • A disconnected agent computer: the application should not claim immediate physical completion.
  • An unavailable printer: inspect the job history and printer status rather than assuming submission failed.
  • A legitimate reprint: it should use a newly authorized request record.
  • An oversized PDF: the function should return its explicit application-limit error.

Also test paper size and orientation with your actual documents. A valid API request cannot correct a badly sized source PDF or an inappropriate printer configuration.

Start with one document and one printer

Reliable Supabase printing needs three clear boundaries: the user must be allowed to request the operation, the backend must control its destination, and retries must preserve its identity. Once those are in place, an Edge Function can connect private application PDFs to physical printers with a small HTTPS integration.

PrintScaler’s Free plan includes 100 prints per month and one computer, with all printers on that computer. Billing is per print request, not per page; review the current plans as your volume grows.

Create a free PrintScaler account, connect one printer, and test a single authenticated print request before adding automated dispatch and status tracking.

Frequently asked questions

Can Supabase print directly to a USB printer?

A cloud-hosted Supabase Edge Function cannot directly access a USB printer connected to a user's computer. It can submit a job to PrintScaler, whose agent connects the local printer to the cloud service.

Can I print from Supabase without a browser print dialog?

Yes. Your application can invoke an authenticated Edge Function that submits a print job through the PrintScaler API. Because delivery happens through the printing service and agent, the browser does not need to open its print dialog.

Should my Supabase Storage PDFs be public for printing?

No. An authorized Edge Function can download a private PDF and send it using PrintScaler's pdf_base64 content type. This also avoids relying on a signed document URL that could expire before an offline printer computer reconnects.

Where should I store my PrintScaler API key in Supabase?

Store it as an Edge Function secret and read it server-side. Never include it in frontend code, browser-accessible configuration, or a database row that ordinary users can read.

How do I prevent duplicate prints when an Edge Function is retried?

Assign one stable identifier to each intended print operation and use it to build the X-Idempotency-Key header. Reuse that key on retries, and create a new authorized operation only when another physical copy is actually intended.

Does a successful Edge Function response mean the PDF has printed?

Not necessarily. In this example, success means PrintScaler accepted the submission. Track print-job states separately through the API or signed webhooks, and do not equate acceptance with physical output.

Related articles