Skip to main content
⚡ Node.js SDK

Get Diesel Prices in Node.js

Install in 30 seconds. Get real-time diesel prices from 130,000+ US gas stations.

Quick Start (3 Steps)

1

Install SDK

npm install @oilpriceapi/client
2

Get API Key

Free tier includes unlimited state averages. Sign up in 30 seconds.

Get free key →
3

Start Querying

Get diesel prices for any state, city, or specific gas station.

✨ Full TypeScript Support: Get type safety and autocomplete out of the box

Get State Diesel Average (FREE)

import { OilPriceAPI } from '@oilpriceapi/client';

const client = new OilPriceAPI({ apiKey: 'YOUR_API_KEY' });

// Get California diesel price
const caDiesel = await client.dieselPrices.getRegional({ state: 'CA' });

console.log(`California diesel: $${caDiesel.price}/gal`);
console.log(`Last updated: ${caDiesel.updatedAt}`);

// Output:
// California diesel: $4.86/gal
// Last updated: 2025-12-15T00:00:00Z

TypeScript Example with Type Safety

import { OilPriceAPI, DieselPrice } from '@oilpriceapi/client';

const client = new OilPriceAPI({ apiKey: process.env.OPA_API_KEY! });

// Get all state prices with type safety
const states = ['CA', 'TX', 'FL', 'NY', 'PA'] as const;
const prices: DieselPrice[] = [];

for (const state of states) {
  const data = await client.dieselPrices.getRegional({ state });
  prices.push(data);
}

// Sort by price (TypeScript knows .price exists!)
prices.sort((a, b) => a.price - b.price);

// Show cheapest 5 states
prices.slice(0, 5).forEach((p) => {
  console.log(`${p.state}: $${p.price}/gal`);
});

Get Cheapest Stations in a City ($0.024/query)

import { OilPriceAPI } from '@oilpriceapi/client';

const client = new OilPriceAPI({ apiKey: 'YOUR_API_KEY' });

// Get cheapest diesel in Los Angeles
const stations = await client.dieselPrices.getStations({
  lat: 34.0522,
  lng: -118.2437,
  radius: 8047  // 5 miles in meters
});

// Sort by price
const sorted = stations.sort((a, b) => a.dieselPrice - b.dieselPrice);

// Show top 10
sorted.slice(0, 10).forEach((station, i) => {
  console.log(`#${i + 1}: ${station.name}`);
  console.log(`   $${station.dieselPrice}/gal`);
  console.log(`   ${station.address}\n`);
});

Build a REST API with Express.js

import express from 'express';
import { OilPriceAPI } from '@oilpriceapi/client';

const app = express();
const client = new OilPriceAPI({ apiKey: process.env.OPA_API_KEY! });

// Endpoint: Get diesel price for any state
app.get('/api/diesel/:state', async (req, res) => {
  try {
    const { state } = req.params;
    const data = await client.dieselPrices.getRegional({
      state: state.toUpperCase()
    });

    res.json({
      state: state.toUpperCase(),
      price: data.price,
      updatedAt: data.updatedAt
    });
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch price' });
  }
});

// Endpoint: Compare multiple states
app.post('/api/diesel/compare', async (req, res) => {
  const { states } = req.body; // ['CA', 'TX', 'FL']

  const results = await Promise.all(
    states.map(async (state: string) => {
      const data = await client.dieselPrices.getRegional({ state });
      return { state, price: data.price };
    })
  );

  res.json({ results });
});

app.listen(3000, () => {
  console.log('Diesel API server running on port 3000');
});

Use in Next.js with Server Components

// app/diesel/[state]/page.tsx
import { OilPriceAPI } from '@oilpriceapi/client';

const client = new OilPriceAPI({ apiKey: process.env.OPA_API_KEY! });

export default async function StateDieselPage({
  params
}: {
  params: { state: string }
}) {
  // Fetch diesel price on the server
  const dieselData = await client.dieselPrices.getRegional({
    state: params.state.toUpperCase()
  });

  return (
    <div>
      <h1>{params.state.toUpperCase()} Diesel Prices</h1>
      <p className="text-4xl font-bold">
        ${dieselData.price.toFixed(3)}/gal
      </p>
      <p>Last updated: {new Date(dieselData.updatedAt).toLocaleDateString()}</p>
    </div>
  );
}

// Generate static pages for all states at build time
export async function generateStaticParams() {
  return ['CA', 'TX', 'FL', 'NY', 'PA'].map((state) => ({
    state: state.toLowerCase()
  }));
}

What Can You Build?

🚀

REST APIs

Build production APIs with Express.js, Fastify, or NestJS that serve diesel prices.

See example →

Real-Time Apps

Create dashboards with Next.js, React, or Vue that show live diesel prices.

See example →
📱

Mobile Apps

Integrate diesel prices into React Native or Ionic apps for drivers and fleet managers.

See example →

Simple, Transparent Pricing

State Averages

FREE
  • Unlimited queries
  • All 50 US states
  • Weekly EIA updates
  • Perfect for web apps

Station-Level Prices

$0.024

per query

  • 130,000+ US gas stations
  • 24-hour updates
  • GPS coordinates included
  • Perfect for mobile apps

Frequently Asked Questions

How do I install the Node.js SDK?

Install via npm or yarn in one command:

npm install @oilpriceapi/client
yarn add @oilpriceapi/client

Does it work with TypeScript?

Yes! The SDK is written in TypeScript and provides full type definitions out of the box. You get autocomplete and type safety automatically.

Can I use this in Next.js?

Absolutely! The SDK works perfectly with Next.js Server Components, API Routes, and Client Components. See our Next.js integration example above.

What about error handling?

The SDK throws typed errors that you can catch and handle. All API errors include status codes and detailed error messages.

Ready to Start Building?

Get your free API key and start querying diesel prices in Node.js today