1

I need a route in website build with nextjs that sends javascript that can be used on different website to do some things.

I created new file in pages/api, let's call it sendTest.ts so it's location is pages/api/sendTest.ts. In the same folder I crated test.ts file that I want to send from sendTest.ts.

sendTest.ts

import type { NextApiRequest, NextApiResponse } from 'next'
import fs from 'fs';
import path from 'path'

const filePath = path.join(__dirname, 'test.js');
const file = fs.readFileSync(filePath);

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  res.setHeader('Content-Type', 'text/javascript');
  res.status(200).send(file)
}

test.ts

console.log('hello');

After build nextjs serves that file at website.com/api/sendTest but after bundling it ends up as

"use strict";
(() => {
var exports = {};
exports.id = 318;
exports.ids = [318];
exports.modules = {

/***/ 211:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {

__webpack_require__.r(__webpack_exports__);
console.log("hello there");



/***/ })

};
;

// load runtime
var __webpack_require__ = require("../../webpack-api-runtime.js");
__webpack_require__.C(exports);
var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId))
var __webpack_exports__ = (__webpack_exec__(211));
module.exports = __webpack_exports__;

})();

which when used in different page as

<script src="website.com/api/sendTest"></script>

results in error

Uncaught ReferenceError: require is not defined
at sendTest:22:27
at sendTest:28:3

My question is how can I force nextjs to skip loading webpack into that file and just allow typescript to change content into javascript and serve file as is? Or is there better way to do what I want, which is sending javascript from specified nextjs route?

Neidd
  • 61
  • 6

1 Answers1

0

Got it.

I changed

const filePath = path.join(__dirname, 'test.js');

to

const filePath = path.resolve('.', 'script/test.js');

and put my script file into folder called script (name doesn't matter) in the main directory

Neidd
  • 61
  • 6