Sending Django requests to NextJS with data

1k views Asked by At

I am looking at integrating NextJS into an existing Django project. The project makes heavy use Django templates for most of its pages and I am looking at modernising the project by taking advantage of React and building out a design / component system. The idea is that we would look at replacing Django with NextJS eventually.

I have been able to use Django to proxy a request through to NextJS, and it works great! I have also been able to send data directly to the NextJS route so that I do not have to call back to Django to get data. This approach annoyingly has the limitation of only sending key/value data.

Here is the working code.

# django
def get(self, request, *args, **kwargs):
  data = request.GET
  return self._handle_request(data, requests.post)

def _handle_request(self, data, make_request):
  data = {"hello": "world"}
  response = make_request("http://localhost:3000", data=data)
  return HttpResponse(response)
//nextjs 
import parse from "urlencoded-body-parser";

export async function getServerSideProps(context) {
  const { req } = context;
  const props = await parse(req);
  return { props };
};

So with this in mind, is there a better way to achieve sending data to a NextJS route without having to do a callback?

1

There are 1 answers

0
Charklewis On BEST ANSWER

After some research I was able to achieve this by using application/json content type.

class NextJsView(WhiteLabelMixin, View):
    def get(self, request, *args, **kwargs):
        data = request.GET
        return self._handle_request(data, requests.post)

    def _handle_request(self, data, make_request):
        data = {"hello": {"dark": "world"}}
        response = make_request("http://localhost:3000", json=json.dumps(data))
        return HttpResponse(response)
import getRawBody from "raw-body";

export async function getServerSideProps(context) {
  const { req } = context;
  let props = {};
  if (req.method == "POST") {
    const body = await getRawBody(req);
    props = JSON.parse(JSON.parse(body));
  }
  return { props };
}