Next.js Discord

Discord Forum

Route GET with @napi-rs/canvas

Unanswered
Willow shoot sawfly posted this in #help-forum
Open in Discord
Avatar
Willow shoot sawflyOP
# next.config.mjs:
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false,
  webpack: (config) => {
    config.externals.push({
      sharp: "commonjs sharp",
      canvas: "commonjs canvas",
    });
    return config;
  },
  images: {
    domains: ["cdn.discordapp.com"],
  },
};

export default nextConfig;


# route.ts:
import { NextRequest, NextResponse } from "next/server";
import { Canvas } from "@napi-rs/canvas";

export async function GET(req: NextRequest) {
  const canvasSize = { width: 720, height: 2080 };
  const colors = {
    background: {
      "color1": "#e1ab94",
      "color2": "#a27c7c"
    },
    texts: {
      bold: "#a66868",
      regular: "#ffffff"
    }
  }

  const canvas = new Canvas(canvasSize.width, canvasSize.height);
  const ctx = canvas.getContext("2d");

  const background = ctx.createLinearGradient(0, canvasSize.height, canvasSize.width, 0);
  background.addColorStop(0, colors.background.color1);
  background.addColorStop(1, colors.background.color2);

  ctx.fillStyle = background;
  ctx.fillRect(0, 0, canvasSize.width, canvasSize.height);

  const buffer = canvas.toBuffer("image/png");

  return new Response(buffer, {
    status: 200,
    headers: {
      "Content-Type": "image/png",
      "Content-Length": buffer.length.toString()
    }
  })
}


error:
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

0 Replies